These are my two structs:
typedef struct _card {
int suit;
int value;
} card;
typedef struct _deck {
int num_cards;
card *cards;
} deck;
This is my make a card function:
card *make_card(int suit, int value)
{
card *newCard = malloc(sizeof(card));
newCard->suit = suit;
newCard->value = value;
return newCard;
}
Now is where I am a bit stuck. I have to make a deck of cards. I know how to assign each value to the card, but I am stumped on how to allocate it in memory. I know it has to do with an array of cards in the deck struct but i cant figure out how.
deck *make_standard_deck()
{
for (int i = 0; i <= 3; i++)
{
for (int j = 1; j <= 13; j++)
{
deck.cards[i] = make_card(int suit, int value);
}
}
}
To create a deck, first allocate memory for the deck structure, and then (assuming that you want an array of pointers to cards) allocate memory for the pointer array. Here's an example that creates a standard deck of 52 cards.
You should allocate the whole array of cards first then assign the individual cards later. Alt. you could also use realloc to make the array increasingly longer but that seems unnecessary here.
first change make_card (and maybe rename it)
then change make_standard_deck
when you free it
If you know before hand the number of cards in the deck (say 52) then you can do it this way:
I'd do something like this
So the deck holds a pointer to an array of cards based off of the decks num_cards value. Of course make sure to actually set num_cards beforehand unlike this example.