C 指结构中的结构,指函数中的结构
在ANSI C中,我尝试使用以下结构将项目添加到链表的末尾:C 指结构中的结构,指函数中的结构,c,function,pointers,struct,linked-list,C,Function,Pointers,Struct,Linked List,在ANSI C中,我尝试使用以下结构将项目添加到链表的末尾: typedef struct items{ char itemname[30]; int damage; int defense; }items; typedef struct itemlist{ struct items item; struct itemlist *next; } itemlist; 简而言之,itemlist是列表中的一个“单元”结构,items是包含数据的内容。我试
typedef struct items{
char itemname[30];
int damage;
int defense;
}items;
typedef struct itemlist{
struct items item;
struct itemlist *next;
} itemlist;
简而言之,itemlist是列表中的一个“单元”结构,items是包含数据的内容。我试着这样称呼他们:
itemlist* additem(itemlist *itemslist, items data){
itemlist *moving, *new;
new = (itemlist*) malloc(sizeof(itemlist));
/* These 3 lines are not working*/
strcpy(new->item->itemname,data->itemname);
new->item->damage = data->damage;
new->item->defense = data->defense;
new->next = NULL;
if (itemslist == NULL) /* empty list? */
return new;
for (moving = itemslist; moving->next != NULL; moving = moving->next);
moving->next = new;
return itemlist;
}
我的问题是,如何在结构类型中引用这些结构?
错误消息如下所示:
错误:“->”的类型参数无效(具有“struct items”)
错误:'->'的类型参数无效(有'items')
感谢您抽出时间项目数据通过值传递给函数,因此您需要使用。运算符,而不是->此处。项目列表中的
项目不是指向项目的指针,而是实际的项目
,因此您不会像中那样使用
new->item.damage
与函数参数data
相同
顺便说一下,在C代码中使用C++代码,如代码>新< /代码>通常是个坏主意。如果你想用C++编译器编译它,那将是一个痛苦。或者更糟的是,如果你在标题中添加了C++关键字,那么你甚至不能将头文件暴露给C++应用程序。如果不是一个结构指针,你只需使用<代码> .<代码>操作符。另外,注意“新”,因为它是C++中的保留关键字。这是一个赋值。@Jonahnson我相信doynax is引用函数的data
参数和data->
操作。Jonah:“data”是通过值传递给additem的,而不是作为指针,所以它必须在赋值中通过“.”而不是“->”来取消引用。这是同样的问题,只是在rhs上,不是吗?他两边都有问题,真正的问题是除了
之外,->
是一个解引用操作符,不需要解引用任何东西。