【发布时间】:2021-12-14 18:55:10
【问题描述】:
对于这些代码行,我收到了以下两个错误以及另外一个“'return': cannot convert from 'link *' to 'link'”。其他两个错误列在问题的主题中。我不知道如何解决这个问题。任何建议都有帮助。
我正在尝试编写纸牌游戏 War 的代码,这就是我目前所拥有的。我在每个间隔测试代码,并在下面列出的代码行中遇到了问题
link NEWnode(Card card, link next) {
link x;
x = malloc(sizeof *x); //allocate memory
if (x == NULL) {
printf("Out of memory. \n");
exit(EXIT_FAILURE);
}
x->next = next;
x->card = card;
return x;
}
整个代码如下:
#include <stdio.h>
#define DECKSIZE 52
typedef int Card;
int rank(Card c) {
return c % 13;
}
// allow for multi-deck war
int suit(Card c) {
return (c % 52) / 13;
}
// representing the cards
void showcard(Card c) {
switch (rank(c)) {
case 0: printf("Deuce of "); break;
case 1: printf("Three of "); break;
case 2: printf("Four of "); break;
case 3: printf("Five of "); break;
case 4: printf("Six of "); break;
case 5: printf("Seven of "); break;
case 6: printf("Eight of "); break;
case 7: printf("Nine of "); break;
case 8: printf("Ten of "); break;
case 9: printf("Jack of "); break;
case 10: printf("Queen of "); break;
case 11: printf("King of "); break;
case 12: printf("Ace of "); break;
}
switch (suit(c)) {
case 0: printf("Clubs\n"); break;
case 1: printf("Diamonds\n"); break;
case 2: printf("Hearts\n"); break;
case 3: printf("Spades\n"); break;
}
}
// testing the code
// representing the deck and hands (with linked lists because need direct access to top and bottom cards, draw cards from top, won cards go to bottom)
typedef struct node* link;
struct node {
Card card;
link next;
};
link Atop, Abot;
link Btop, Bbot;
// showing a hand
void showpile(link pile) {
link x;
for (x = pile; x != NULL; x = x->next)
showcard(x->card);
}
int countpile(link pile) {
link x;
int cnt = 0;
for (x = pile; x != NULL; x = x->next)
cnt++;
return cnt;
}
// Creating the 52 card Deck
#include <stdlib.h> //for malloc()
link NEWnode(Card card, link next) {
link x;
x = malloc(sizeof *x); //allocate memory
if (x == NULL) {
printf("Out of memory. \n");
exit(EXIT_FAILURE);
}
x->next = next;
x->card = card;
return x;
}
link makepile(int N) {
link x = NULL;
Card c;
for (c = N - 1; c >= 0; c--)
x = NEWnode(c, x);
return x;
}
// testing the code
int main(void) {
link deck;
deck = makepile(DECKSIZE);
showpile(deck);
return 0;
}
【问题讨论】:
-
不要
typedef指针。它让每个人都感到困惑,包括你自己。 -
什么是
link? -
OT:不要考虑
printf("Out of memory. \n");,而是考虑perror("malloc");,它会为您提供更多信息。 -
编辑问题以提供minimal reproducible example。
-
我怀疑显示的代码是否与产生报告的错误消息的代码相同。函数返回类型和
x都声明为link,因此return x;不会产生“'return': cannot convert from 'link *' to 'link'”。
标签: c linked-list malloc