Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a new instance of a struct

Tags:

What is the correct way to create a new instance of a struct? Given the struct:

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

I've seen two ways..

The first way (xCode says this is redefining the struct and wrong):

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

The second way:

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

Alternatively, is there another way?

like image 919
Robin Huang Avatar asked Sep 15 '15 04:09

Robin Huang


1 Answers

It depends if you want a pointer or not.

It's better to call your structure like this :

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

After to instanciate it for a no-pointer structure :

t_data my_struct; my_struct.a = 8; 

And if you want a pointer you need to malloc it like that :

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

I hope this answers your question.

like image 143
Prog_is_life Avatar answered Oct 05 '22 00:10

Prog_is_life