问题
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