Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

c - Initializing a struct with malloc

To create a struct I can do one of the following:

// Method 1
Item *item = malloc(sizeof(Item));
Item _item = {.name="job"};
item = &_item;

// Method 2
Item *item = malloc(sizeof(Item));
item->name="job";

Is there a simpler method to do this? Perhaps something along the lines of:

malloc(sizeof(Item)) & (Item) {.name="job"}

Here are the two methods: https://godbolt.org/z/MfYGW3

question from:https://stackoverflow.com/questions/65945828/initializing-a-struct-with-malloc

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Are you looking for something like this?

#include <stdlib.h>

typedef struct {
    const char* name;
} Item;

int main() {
    Item* item = malloc(sizeof(Item));
    *item = (Item){.name = "Hello"};
    // do work    
    free(item);
    return 0;
}

Compiles with GCC 10.2.0 -Wall -Wextra with no errors or warnings.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...