【发布时间】:2016-11-06 07:24:59
【问题描述】:
我似乎无法弄清楚如何设置我的 printf 语句,以便能够打印我传递给 print 函数的结构数组的所有元素。
当我尝试编译时,我收到警告:
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];
指针新手,不知道如何解决这个问题。
【问题讨论】:
-
您的示例没有足够的信息来帮助您。尝试将您的示例缩小为可编译且仅约 20-30 行长的示例。 (您可能会通过这种方式自己发现问题!)
-
而且错误信息很清楚。您传递的参数类型错误。
-
尝试解析警告。它实际上是想告诉你一些重要的事情,而这件重要的事情不是“你可以用演员来摆脱我”。
-
提供
struct的结构。试试%c -
您真的认为问题在于您要打印数组中结构的 all 值吗?你不觉得问题可能比这更简单吗?