c - 在结构中引用结构,在函数中引用结构

标签 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 是包含数据的内容。我尝试这样调用它们:

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/

相关文章:

c - 如何检查 LsaLogonUser session ,或者在 wine 下创建一个 session

javascript - 将 JavaScript 源文件的全部内容包装在函数 block 中的意义和原因是什么?

c - 是否可以在 C 中编写您自己的 kbhit()?

c - 此代码是否正确?如果是,则 malloc 已经将地址分配给 name[i] 变量,那么为什么使用 strcpy?

c - 当我读取文件时如何摆脱 "if"?

c - 如何在指向字符串的指针上使用 toupper()?

c - 如果有任何未发现的错误,如何测试字数统计程序?

php - 如何在 PHP GET URL 变量(或函数参数)中使用&符号?

c - 为什么在 C 中将类型定义为指向未定义结构的指针是有效的?

c++ - auto 如何推导指针类型?