我正在尝试创建一个简单的单链表。以前,我成功地做到了这一点,没有任何错误,但现在我遇到了错误。我怀疑内存分配存在某种问题,因为if
第 23 行的声明。
我尝试过的:
我在所有声明中都使用了类型转换,尽管这在 C 中不是必需的。
我删除了if
声明,我仍然遇到错误。
这是我的代码:
#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;
声明一个名为的类型别名Product
for an unnamed结构 - 但是你需要一个named前向声明的结构struct Product *next;
,否则编译器无法确定它属于哪个定义。
最简单的解决方案是为结构体命名:
typedef struct Product
{
int value;
struct Product *next;
} Product;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)