I'm trying to write a C code to represent a deck of cards by first creating the struct for a card, and then copying the strings from 2D arrays into the suits and ranks of those cards.
The program doesn't return any faults, but when I tried to display the cards the character are all mixed up or just the first character got displayed. How could I fix this?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char ranks[13][10] = {"Ace", "Two", "Three", "Four", "Five", "Six", "Seven",
"Eight", "Nine", "Ten", "Jack", "Queen", "King"};
char suits[4][10] = {"Clubs", "Diamonds", "Hearts", "Spades"};
typedef struct{
char rank;
char suit;
int value;
}card;
void initialize(card *s){
//s = (person*) malloc(1 * sizeof( person));
for (int i = 0; i < 52; i++){
strcpy(&(s+i)->rank , ranks[i % 13]);
strcpy(&s[i].suit , suits[i / 13]);
(s+i)->value = i % 13 +1;
}
}
int main(){
card *p;
initialize(p);
for (int i = 0; i < 52 ; i++){
printf("%s is %s\n", &p[i].rank, &p[i].suit);
}
return 0;
}
the output is sth like this
AClu is Clu
TClu is Clu
TClu is Clu
FClu is Clu
FClu is Clu
SClu is Clu
SClu is Clu
ECl is Clu
NClu is Clu
TClu
is Clu
JClu
is Clu
pand make changes as*sinsideinitializecharnotchar []you cantstrcpyto it