【问题标题】:Editing an array of strings in c在c中编辑字符串数组
【发布时间】:2017-11-15 03:13:03
【问题描述】:

我正在为扑克游戏编写代码,并且在我的 ma​​in 函数中我有:

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 语句中的代码很好。 当我尝试打印提供给手的值时,ma​​in() 中出现了问题,但是在 deal() 中,手上的值打印正常。我假设我没有正确地将手传递给函数,但是无论我尝试使用不同的方法使程序正确运行,都没有任何效果。

可以在此处看到该程序的示例: Example of program running

【问题讨论】:

  • 所以你只显示有效的东西而不是无效的东西?请提供 MCVE stackoverflow.com/help/mcve
  • 我提供了导致手头问题的代码,并省略了不会导致问题的不相关代码。
  • 好吧,那我理解错了。但始终包含一个 MCVE。我们应该能够或多或少地将您的代码复制到编辑器并运行它,问题就会出现。

标签: c pointers poker arrayofstring


【解决方案1】:

在你deal()函数中:

hand[card - 1] = str;

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

例如

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

【讨论】:

    猜你喜欢
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多