Search code examples
cpointerspokerarrays

Editing an array of strings in c


I'm writing code for a poker game and in my main function I have:

const char *suits[4] = { "Spades", "Clubs", "Hearts", "Diamonds" };
const char *faces[13] = { "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" };

int deck[4][13] = { 0 };

srand((unsigned)time(NULL));

char *hand[5] = { "\0" };

shuffle(deck);
deal(deck, faces, suits, hand);

for (int i = 0; i < 5; i++) {
    printf("%s", hand[i]);
}

This is where my general problem is. hand wont print out the values given to it in deal, which are 5 cards.

shuffle() simply shuffles the deck, no errors there so I am not going to include it in this question.

deal() has the following code (ignore the curly-bracket/whitespace discrepancies, I'm still adjusting to the formatting of this site):

void deal(const int wDeck[][13], const char *wFace[], const char *wSuit[], 
char *hand[]) {

int row = 0;    /* row number */
int column = 0; /*column number */
int card = 0;   /* card counter */

                /* deal 5 of the 52 cards */
for (card = 1; card <= 5; card++)
{
    /* loop through rows of wDeck */
    for (row = 0; row <= 3; row++)
    {
        /* loop through columns of wDeck for current row */
        for (column = 0; column <= 12; column++)
        {
            /* if slot contains current card, deal card */
            if (wDeck[row][column] == card)
            {
                char str1[10];
                strcpy(str1, wFace[column]);
                char str2[10];
                strcpy(str2, wSuit[row]);
                char str3[6] = " of ";
                char str[26] = "";
                strcat(str, str1);
                strcat(str, str3);
                strcat(str, str2);
                puts(str);

                hand[card - 1] = str;
                printf("%s\n", hand[card - 1]);
            }
         }
      }
   }
}

The code in the if statement works just fine. The problem arises in main() when I try to print the values given to hand, however in deal() the values in hand print fine. I assume that I am not passing hand into the function correctly, but no matter the different methods I've tried to get the program to run correctly, nothing works.

An example of the program as is can be seen here: Example of program running


Solution

  • in you deal() function:

    hand[card - 1] = str;
    

    str is local character array whose address will get invalidated once you return from deal() right way to do it will be allocate memory to each element(max number of elements being 5) of hand, then copy value of str using strcpy into element of hand

    e.g.

     hand[card - 1] = malloc(26);
     strcpy(hand[card - 1],str);