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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32577808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 12:07:47  来源:igfitidea点击:

How to create a new instance of a struct in C

cstructinstance

提问by Robin Huang

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

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

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

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

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

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

The second way:

第二种方式:

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

Alternatively, is there another way?

或者,还有其他方法吗?

采纳答案by Robin Huang

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:

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

struct listitem newItem;

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

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

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

回答by Prog_is_life

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 :

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

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

I hope this answer to your question

我希望这能回答你的问题

回答by Scott G.

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

这是结构的简要概述:http: //www.cs.usfca.edu/~wolber/SoftwareDev/C/CStructs.htm