Reputation: 773
Below is an MRE and the OUTPUT (truncated). When I use gdb, I confirm that each element of my deck array contains each individual card. However, when I iterate through the deck array, all the cards are the Ace of Spades. Why? I've attempted due diligence. The program compiles and runs. The logic seems correct.
COMPILE
gcc -g prog33.c -o prog33.exe -Wall
MRE
//includes
#include <stdio.h>
#define DECK 52
//variable and function declarations
enum suit { clubs, diamonds, hearts, spades };
enum value { two, three, four, five, six, seven, eight, nine, ten, jack, queen, king, ace };
char *Suit[] = {"Clubs","Diamonds","Hearts","Spades" };
char *Values[] = {"Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King","Ace" };
char *deck[DECK];
char mycard[20];
//main function
int main(int argc, char *argv[])
{
printf("prog33.c, enums\n");
for(int s = clubs; s <= spades; s++)
{
printf("%d. %s\n", s, Suit[s]);
for(int v = two; v <= ace; v++)
{
int idx = (s*13) + v;
sprintf(mycard, "%s of %s", Values[v], Suit[s]);
printf(" %d, %s, %d, --- %s\n", v, Values[v], idx, mycard);
deck[idx] = mycard;
printf(" %i. %s\n", idx, deck[idx]);
}
};
for(int i = 0; i < DECK; i++) printf("%d. %s\n", i, deck[i]);
return 0;
}
OUTPUT (truncated)
...
11, King, 24, --- King of Diamonds
24. King of Diamonds
12, Ace, 25, --- Ace of Diamonds
25. Ace of Diamonds
2. Hearts
0, Two, 26, --- Two of Hearts
26. Two of Hearts
1, Three, 27, --- Three of Hearts
27. Three of Hearts
2, Four, 28, --- Four of Hearts
28. Four of Hearts
3, Five, 29, --- Five of Hearts
29. Five of Hearts
4, Six, 30, --- Six of Hearts
30. Six of Hearts
...
21. Ace of Spades
22. Ace of Spades
23. Ace of Spades
24. Ace of Spades
25. Ace of Spades
26. Ace of Spades
27. Ace of Spades
28. Ace of Spades
29. Ace of Spades
...
Upvotes: 0
Views: 67
Reputation: 152
Try it.You will find why.
#include <stdio.h>
#include <string.h>
#define DECK 52
//variable and function declarations
enum suit { clubs, diamonds, hearts, spades };
enum value { two, three, four, five, six, seven, eight, nine, ten, jack, queen, king, ace };
char *Suit[] = {"Clubs","Diamonds","Hearts","Spades" };
char *Values[] = {"Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King","Ace" };
char deck[DECK][128];
char mycard[20];
//main function
int main(int argc, char *argv[])
{
printf("prog33.c, enums\n");
for(int s = clubs; s <= spades; s++)
{
printf("%d. %s\n", s, Suit[s]);
for(int v = two; v <= ace; v++)
{
int idx = (s*13) + v;
sprintf(mycard, "%s of %s", Values[v], Suit[s]);
printf(" %d, %s, %d, --- %s\n", v, Values[v], idx, mycard);
strcpy(deck[idx], mycard);
printf(" %i. %s\n", idx, deck[idx]);
}
};
for(int i = 0; i < DECK; i++) printf("%d. %s\n", i, deck[i]);
return 0;
}
Upvotes: 2