why can't I use partial struct initialization

2019-08-10 01:00发布

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?

标签: c struct alloc
2条回答
淡お忘
2楼-- · 2019-08-10 01:35

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.

查看更多
男人必须洒脱
3楼-- · 2019-08-10 01:41

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.

查看更多
登录 后发表回答