我想在C中创建一个链表,但是当我使用下面的代码时,gcc抛出了这个错误:
错误:'->'类型参数无效(有'struct list')
代码是:
#include <stdio.h>
#include <stdlib.h>
struct list{
int age;
struct list *next;
};
void create_item(int *total_items,
struct list where_is_first_item,
struct list where_is_last_item)
{
struct list *generic_item;
generic_item = malloc(sizeof(struct list));
printf("nage of item %d: ", (*total_items)+1);
scanf("%d", &generic_item->age);
if(*total_items == 0){
where_is_first_item->next=generic_item;
where_is_last_item->next=generic_item;
printf("nitem createdn");
}
else{
where_is_last_item->next=generic_item;
printf("nitem createdn");
}
int main (void){
struct list *where_is_first_item;
struct list *where_is_last_item;
int total_items=0;
printf("nntCREATE A NEW ITEMn");
create_item(&total_items, where_is_first_item, where_is_last_item);
total_items++;
return 0;
}
void create_item(int *total_items, struct list *where_is_first_item, struct list *where_is_last_item)
添加一个星号!
你也引用无效内存,因为你分配给generic_item
,然后引用where_is_first_item
。where_is_first_item
未被分配。在使用where_is_first_item
之前先试试where_is_first_item = generic_item;
。
您还会发现main
函数中的指针保持未修改,因为指针值正在传递。这里它变得令人困惑/有趣:如果你想修改main
中的指针,你需要将指针传递给指针: struct_list **where_is_first_item
。相信我,那可能会让你头疼。
您忘记将结构体参数作为指针传递。
改变:
create_item(int *total_items, struct list where_is_first_item, struct list where_is_last_item)
:
create_item(int *total_items, struct list *where_is_first_item, struct list *where_is_last_item)