How to create a new instance of a structure in C

In C, when you define a structure. What is the correct way to create a new instance? I saw two ways:

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

The first way (xCode says this is a redefinition of the structure and wrong):

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

The second way:

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

Alternatively, is there another way?

+5
source share
3 answers

The second method only works if you used

 typedef struct listitem listitem; 

before any variable declaration of type listitem . You can just statically distribute the structure, rather than dynamically allocate it:

 struct listitem newItem; 

You have demonstrated how to do the following for each int you want to create:

 int *myInt = malloc(sizeof(int)); 
+8
source

It depends on whether you want a pointer or not.

It is better to name your structure as follows:

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

After creating it for a structure without a pointer:

 t_data my_struct; my_struct.a = 8; 

And if you want a pointer, you need to do this:

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

I hope this answer to your question

+7
source
 struct listitem newItem; // Automatic allocation newItem.val = 5; 

Here is a brief description of the structures: http://www.cs.usfca.edu/~wolber/SoftwareDev/C/CStructs.htm

+2
source

All Articles