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

自闭症网瘾萝莉.ら 提交于 2019-12-24 17:17:35

问题


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?


回答1:


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.




回答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.



来源:https://stackoverflow.com/questions/28545491/why-cant-i-use-partial-struct-initialization-for-a-malloced-struct-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!