简体   繁体   中英

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

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM