How to create a new instance of a struct in C

被刻印的时光 ゝ 提交于 2019-11-29 17:23:30

问题


In C, when you define a struct. What is the correct way to create a new instance? I've seen two ways:

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

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?


回答1:


The second way only works if you used

typedef struct listitem listitem;

before any declaration of a variable with type listitem. You can also just statically allocate the structure rather than dynamically allocating it:

struct listitem newItem;

The way you've demonstrated is like doing the following for every int you want to create:

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



回答2:


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 answer to your question




回答3:


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

Here's a quick rundown on structs: http://www.cs.usfca.edu/~wolber/SoftwareDev/C/CStructs.htm



来源:https://stackoverflow.com/questions/32577808/how-to-create-a-new-instance-of-a-struct-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!