Search code examples
cstructure

Copy a string on a structure element in C


I don't understand why my string is not copied.

The strings structures are similar to this one "KS 2H 5C JD TD"

Here is my code (the comments are all that I tried (memcpy and strcpy)):

typedef struct Hand Hand;
struct Hand {
    char *cards;
    double power;
};
Hand* initHand(char *set){
    Hand *hand = malloc(sizeof(*hand));
    if(hand == NULL)
        exit(EXIT_FAILURE);

    char card[5][3];
    //strcpy(hand->cards,*cards);
    int i=0;
    char *p = strtok (set, " ");

    while (p != NULL)
    {
        card[i] = p;
        printf("%s\n",p);
        p = strtok (NULL, " ");
        i++;
    }

    hand->power=0;
}

I was willing to copy every 2 letters in an array with strtok (this is what I wanna do); then I tried to copy the whole string.


Solution

  • Thanks a lot. I understood my mistakes:

    Mistakes:

    • I didn't know that strtok is a destructive function (I was trying to edit a readonly data since I was using a constant).
    • I didn't allocate memory for char *cards

    Solution:

    • make a copy of the set.
    • allocate memory.

    Here's the code that worked for me:

    struct Hand {
        char cards[5][3];
        double power;
    };
    
    
    Hand* initHand(char *set){
        Hand *hand = malloc(sizeof(*hand));
        if(hand == NULL)
            exit(EXIT_FAILURE);
    
        char copy_set[15]="";
        strcpy(copy_set,set);
    
        char **str = (char**) malloc(5*sizeof(char*));
        for(int i=0; i<3; i++){
            str[i]= (char) malloc(3*sizeof(char));
        }
        strcpy(hand->cards,str);
    
        int i=0;
        char *p = strtok (copy_set, " ");
    
        while (p != NULL)
        {
            strcpy(hand->cards[i], p);
            p = strtok (NULL, " ");
            i++;
        }
        
        hand->power=0;
        return hand;
    }