在c中编辑字符串数组

时间:2017-11-15 03:13:03

标签: c pointers poker arrayofstring

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

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

这是我的一般问题所在。手不会打印出交易中给出的值,即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()中,手中的值打印正常。我假设我没有正确地传递函数,但无论我试图让程序正确运行的不同方法,没有任何作用。

这里可以看到程序的一个例子: Example of program running

1 个答案:

答案 0 :(得分:0)

你在deal()函数中的

hand[card - 1] = str;

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

e.g。

 hand[card - 1] = malloc(26);
 strcpy(hand[card - 1],str);
相关问题