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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With