在 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 是包含数据的内容。我尝试这样调用它们:
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;
}
我的问题是,如何在结构类型中引用这些结构? 错误消息如下:
错误:“->”的类型参数无效(具有“结构项”)
错误:“->”的类型参数无效(有“项目”)
感谢您的宝贵时间
最佳答案
itemlist
中的 item
不是指向 item
的指针,而是实际的 item
,因此您不需要不要使用 ->
,而是使用 .
。
new->item.damage
与函数参数data
相同。
顺便说一句,在 C 代码中使用像 new
这样的 C++ 关键字通常是一个坏主意。如果你想用 C++ 编译器来编译它,那将会很痛苦。或者更糟糕的是,如果您最终在 header 中使用了 C++ 关键字,那么您甚至无法将 header 公开给 C++ 应用程序。
关于c - 在结构中引用结构,在函数中引用结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20447353/