why can't I use partial struct initialization for a malloced struct in C
Asked Answered
A

2

1

Apperently in C99 you can simply initialize a statically allocated struct in this way

struct sometype {
   int a;
   double b;
};
sometype a = {
   .a = 0;
};

Well, this does not apply to a struct on heap like this.

struct sometype *a = malloc(sizeof(struct sometype));
*a = {
   .a = 0;
 };

With GCC 4.9.2, the compiler complained

error: expected expression before '{' token

I know this is silly, but is there any syntax or technical reason that I cannot do this?

Abducent answered 16/2, 2015 at 16:2 Comment(2)
Where is the malloc that you promised? And you realise that there is no type named sometype? There is only a struct sometype, not a sometype.Sempiternal
@Sempiternal Well, that was just a illustration, I wasn't so carefull on that, since the second piece code was important.Abducent
H
5

There is a difference between struct initialization, and assignment.

When using heap memory, it's always assignment, since initialization only happens when you're actually declaring the instance (not just a pointer to an instance).

You can use compound literals:

struct sometype *ms = malloc(sizeof *ms);
*ms = ((struct sometype) { .a = 0 });

But of course this might be worse than just doing:

ms->a = 0;

since it will write to all fields of the structure, setting all the fields that weren't mentioned in the literal to zero. Depending on what you need, this can be needlessly costly.

Hepatic answered 16/2, 2015 at 16:6 Comment(1)
Your last sentence isn't true. If a subobject is missing in an initializer list, it will be initialized implicitly to the (non-random) default value (see the C99 spec, 6.7.8.19). So *ms = ((struct sometype) { .a = 0 }) will set ms->b to 0.0.Duron
P
2

Well, this does not apply to a struct on heap.

Yes. It will not. That's because there is a difference in initialization and assignment. In case of

sometype a = {.a =0};  

this is initialization. In case of dynamic allocation

sometype *a = malloc(sizeof(struct sometype);
*a = {.a =0};   

there is assignment.

Plumy answered 16/2, 2015 at 16:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.