我正在为扑克游戏编写代码,在我的main函数中我有:
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 的值时,问题出现在 main() 中,但是在 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/