c - 在c中编辑字符串数组

标签 c pointers poker arrayofstring

我正在为扑克游戏编写代码,在我的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 语句中的代码工作得很好。 当我尝试打印提供给 hand 的值时,问题出现在 ma​​in() 中,但是在 deal() 中,hand 中的值打印得很好。我假设我没有正确地将手传递到函数中,但是无论我尝试使用不同的方法让程序正确运行,都不起作用。

该程序的示例如下: Example of program running

最佳答案

在你的deal()函数中:

hand[card - 1] = str;

str 是本地字符数组,一旦从 deal() 返回,其地址就会失效 正确的方法是为 hand 的每个元素分配内存(最大元素数量为 5),然后使用 strcpy 复制 str 的值> 进入 hand 元素

例如

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

关于c - 在c中编辑字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47298751/

相关文章:

c++ - C/C++ 中的累积正态分布函数

c - 指针向上转换和向下转换

java - 在数组中查找多对(两对和/或葫芦)

javascript - 有没有比这更简单的方法来计算扑克中的顺子?

c - Segmentation Fault Error Again——使用链表实现栈

c - 删除二叉堆中的最顶层元素

c++ - 对象调用对象

c++ - Auto 和 Void 的区别?

python - python 类中使用的 ctypes 指针导致的内存泄漏

java - 如何使用 Java 和两个嵌套 for 循环计算扑克中的对数