不允许指向不完整类类型的指针 - 单向链表 [英] pointer to incomplete class type is not allowed - singly linked list
问题描述
我正在尝试创建一个简单的单向链表.以前,我成功地做到了这一点,没有错误,但是现在我遇到了错误.由于第 23 行中的 if
语句,我怀疑内存分配存在某种问题.
I'm trying to create a simple singly linked list. Previously, I successfully did this with no errors, however now I encounter an error. I suspect that there is some kind of problem with memory allocation because of the if
statement in line 23.
我尝试过的:
我在所有声明中都使用了类型转换,即使在 C 中没有必要.
I used typecasting in all of my declarations even though it is not necessary in C.
我删除了 if
语句,但仍然遇到错误.
I removed the if
statement and I still encountered the errors.
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int value;
struct Product *next;
} Product;
int main()
{
int user_choice;
Product *head;
head = malloc(sizeof(Product));
head->next = NULL;
head->value = 5;
printf("\n Do you want to add a new node (0 for no, 1 for yes)? \n");
scanf("%d", &user_choice);
if (user_choice == 1) // line 23
{
head->next = malloc(sizeof(Product));
if (!head->next)
printf("\n Memory allocation failed! \n");
head->next->next = NULL; // 1st error
printf("\n Enter a value: \n");
int value;
scanf("%d", &value);
head->next->value = value; // 2nd error
}
free(head);
free(head->next);
}
推荐答案
typedef struct
{
} Product;
为一个 unnamed 结构声明一个名为 Product
的类型别名 - 但是你需要一个 named 结构用于你的前向声明 struct Product*next;
,否则编译器无法确定它属于哪个定义.
Declares a type alias called Product
for an unnamed struct - however you need a named struct for your forward declaration struct Product *next;
, otherwise the compiler cannot determine which definition it belongs to.
最简单的解决方案是给结构一个名字:
The simplest solution is to give the struct a name:
typedef struct Product
{
int value;
struct Product *next;
} Product;
这篇关于不允许指向不完整类类型的指针 - 单向链表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!