I'm trying to learn some C and I've started with a simple deck of cards program.
The card is struct containing two ints for face and suit. And I'm building a deck by allocating 52 cards, and going thorough a loop.
card *Deck = (card*)malloc(sizeof(card) * 52);
for(int i = 0; i < 4; i++){
for(int j = 1; j < 14; j++){
Deck->face = j;
Deck->suit = i;
Deck += sizeof(card);
}
}
Deck -= sizeof(card) * 52;
printDeck(Deck);
free(Deck);
I have a printCard
function that takes a single pointer and prints the values, and a print deck function that calls printCard
52 times. If i print the cards as they are being created, everything goes well, but if i print the cards after all have been created for some reason I get a segfault at the 6th card. I fired up gdb
and noticed this output:
Seven of Diamonds<br>
(null) of Diamonds<br>
Nine of Diamonds<br>
The rest of the output is normal. When checking for the value of the 6th card i got:
(gdb) p c->face
$10 = 2675
If i am skipping the 6th card the output is fine and everything works the way it should. I'm new to C but i can't really see how that value got put in that field in my code.
struct card{
int face;
int suit;
};
void printCard(card* c){
printf("%s of %s\n", face_str[c->face], suit_str[c->suit]);
}
Edit:
The printDeck code:
Before:
void printDeck(card* c){
for(int i = 0; i < 52; i++){
printCard(c);
c += sizeof(card);
}
}
After:
void printDeck(card* c){
for(int i = 0; i < 52; i++){
printCard(c);
c++;
}
}
printCard didn't changed:
void printCard(card* c){
printf("%s of %s\n", face_str[c->face], suit_str[c->suit]);
}