Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...