Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a one-line initialization for C structs on the heap?

Tags:

c

In C, we can initialize a struct on the stack in the following way.

struct Foo {
    int bar;
    int bar2;
};


int main(){
    struct Foo myFoo = {
        .bar = 1,
        .bar2 = 2
    };
}

However, when, I try this kind of thing the heap, the compiler refused it.

struct Foo* myFooPtr = malloc(sizeof(struct Foo));
*myFooPtr = {
    .bar = 1,
    .bar2 = 2
}

Compiler error:

error: expected expression before ‘{’ token
     *myFooPtr = {

Is there a way to achieve kind of initialization on the heap?

like image 384
merlin2011 Avatar asked Jan 10 '23 23:01

merlin2011


1 Answers

Yes:

struct Foo *myFooPtr = malloc(sizeof(struct Foo));
*myFooPtr = (struct Foo) {
        .bar = 1,
        .bar2 = 2
    };

(although formally this an initialisation of an anonymous compound literal object followed by an assignment to the heap object, rather than a direct initialisation).

like image 152
caf Avatar answered Jan 31 '23 01:01

caf