如何在C中打印struct array的所有值

时间:2016-11-06 07:24:59

标签: c pointers

我似乎无法弄清楚如何设置我的printf语句,以便能够打印我传递给print函数的struct array的所有元素。

当我尝试编译时,我收到警告:

format specifies type 'char *' but the argument has type 'char' [-Wformat]

我尝试过投射,但仍然出错。

当我运行程序时,我得到:

Segmentation fault: 11

以下是代码:

struct Card {
    char suit;
    char face;
};
int main(void)
{
   ...
   struct Card *hand[HAND_SIZE];
   dealHand(deck, face, suit, hand); //deal the deck
   printHand(hand);
}

 void dealHand(unsigned int wDeck[][FACES], const char *wFace[], const char *wSuit[], struct Card *wHand[])
{
    unsigned int c = 0;
    for (size_t card = 1; card <= HAND_SIZE; ++card) {
        for (size_t row = 0; row < SUITS; ++row) {
            for (size_t column = 0; column < FACES; ++column) {
                if (wDeck[row][column] == card){
                    struct Card aCard;
                    aCard.face = wFace[column];
                    aCard.suit = wSuit[row];
                    wHand[0] = &aCard;
                    c = c + 1;
                }
            }
        }
    }
}
void printHand(struct Card *wHand[]) {
    for (unsigned i = 0; i < HAND_SIZE; ++i) {
        printf("%c%c\n", wHand[i]->face, wHand[i]->suit);
    }
}

如何打印结构数组?

编辑:我用%c替换%s但现在收到警告:

incompatible pointer to integer conversion assigning to 'char' from 'const char *' [-Wint-conversion]
                    aCard.face = wFace[column];

指针新手,不知道如何解决这个问题。

1 个答案:

答案 0 :(得分:1)

因为char类型的套装和面孔。您必须在%c中使用printf()

printf("%c%c\n", wHand[i]->face, wHand[i]->suit);