简体   繁体   中英

Problem with assigning char from a 2D array to an array of structs in C

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 

Your structure card have only one elements for storing strings. This isn't enough for storing strings with any positive length (because terminating null-character is required).

You should change the members rank and suit to arrays and allocate enough elements. Also remove & s because then they will be automatically converted to pointers to the first elements.

Also don't forget to allocate some buffer and assign that to p .

#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[10];
    char suit[10];
    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 data[52];
    card *p = data;
    
    initialize(p);

   
    for (int i = 0; i < 52 ; i++){
        printf("%s is %s\n", p[i].rank, p[i].suit);
    }

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM