0

我正在为扑克游戏编写代码,在我的主要功能中,我有:

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]);
}

这是我的一般问题所在。hand 不会打印出在发牌中给它的值,即 5 张牌。

shuffle()只是洗牌,没有错误,所以我不打算将它包含在这个问题中。

deal()具有以下代码(忽略大括号/空白差异,我仍在调整此站点的格式):

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]);
            }
         }
      }
   }
}

if 语句中的代码运行良好。当我尝试打印给手的值时, main()中出现了问题,但是在deal()中,手上的值打印得很好。我假设我没有正确地将手传递给函数,但是无论我尝试使用不同的方法使程序正确运行,都没有任何效果。

可以在此处看到该程序的 示例:程序运行示例

4

1 回答 1

0

在你的deal()功能中:

hand[card - 1] = str;

str是本地字符数组,一旦您从正确的方式返回,其地址将失效deal() ,它将为 的每个元素(最大元素数为 5)分配内存,然后将using的hand值复制到strstrcpyhand

例如

 hand[card - 1] = malloc(26);
 strcpy(hand[card - 1],str);
于 2017-11-15T04:01:53.823 回答