I'm trying to get more comfortable with pointers and C in general so I've been doing practice problem. I have a struct:
typedef struct Card
{
enum { hearts, spades, clubs, diamonds } suit;
int value;
} Card;
and a function used to allocate memory for the deck:
void createDeck(Card ** deck)
{
deck = malloc(52 * sizeof(Card *)); //allocate space for deck
if (deck == NULL)
{
fprintf(stderr, "malloc failed\n");
return;
}
//allocate memory for each card in deck
for (size_t i = 0; i < 52; i++)
{
*(deck + i) = malloc(sizeof(Card));
}
}
and I'm trying to use the code like this:
int main()
{
Card *deck = NULL;
createDeck(&deck);
printf("%d", deck[0].suit)
}
This gives a nullptr error which makes me think I'm not allocating memory correctly. I've changed different things but I can't get this to work regardless. How do I access the members of deck
after I've done work to it with createDeck
?