c -类型为"void *"不能分配给"链接"的空类型.& # 39; = &



我收到了以下两个错误以及另外一个"'return': cannot convert from 'link *' to 'link'"对于这几行代码。另外两个错误列在题目中。我不知道如何解决这个问题。任何建议都是有帮助的。

我正试图编码纸牌游戏战争,这是我到目前为止所拥有的。我在每隔一段时间测试代码,并在下面列出的代码行遇到了问题

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("Clubsn"); break;
case 1: printf("Diamondsn"); break;
case 2: printf("Heartsn"); break;
case 3: printf("Spadesn"); 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;
}

这是因为您使用的是c++编译器而不是C编译器。在c++中,必须对该行进行强制类型转换:

x = (link) malloc(sizeof *x)

…而在C中不需要强制转换——强制转换是隐式进行的——并且在C中添加这样的强制转换实际上被认为是最佳实践。

另一方面,在c++中,您最好避免使用malloc而使用new。但是,由于您的代码打算使用C而不是c++,因此请确保选择C编译器。

相关内容

  • 没有找到相关文章

最新更新