如何在C中创建结构的新实例

在C中,定义结构时。 创建新实例的正确方法是什么? 我见过两种方式:

struct listitem { int val; char * def; struct listitem * next; }; 

第一种方式(xCode说这是重新定义结构和错误):

  struct listitem* newItem = malloc(sizeof(struct listitem)); 

第二种方式:

  listitem* newItem = malloc(sizeof(listitem)); 

或者,有另一种方式吗?

第二种方式只有在你使用时才有效

 typedef struct listitem listitem; 

在任何声明类型为listitem的变量之前。 您也可以静态分配结构而不是动态分配它:

 struct listitem newItem; 

您演示的方式就像为要创建的每个int执行以下操作:

 int *myInt = malloc(sizeof(int)); 

这取决于你是否想要一个指针。

最好像这样调用你的结构:

 Typedef struct s_data { int a; char *b; etc.. } t_data; 

之后将其设置为无指针结构:

 t_data my_struct; my_struct.a = 8; 

如果你想要一个指针,你需要像那样malloc:

 t_data *my_struct; my_struct = malloc(sizeof(t_data)); my_struct->a = 8 

我希望这回答你的问题

 struct listitem newItem; // Automatic allocation newItem.val = 5; 

以下是结构的快速概述: http : //www.cs.usfca.edu/~wolber/SoftwareDev/C/CStructs.htm