为什么我不能对 C 中的 malloced 结构使用部分结构初始化
why can't I use partial struct initialization for a malloced struct in C
显然在 C99 中,您可以用这种方式简单地初始化静态分配的结构
struct sometype {
int a;
double b;
};
sometype a = {
.a = 0;
};
好吧,这不适用于像这样的堆上结构。
struct sometype *a = malloc(sizeof(struct sometype));
*a = {
.a = 0;
};
对于 GCC 4.9.2,编译器有问题
error: expected expression before '{' token
我知道这很愚蠢,但是有什么语法或技术原因我不能这样做吗?
结构初始化和赋值是有区别的。
使用堆内存时,它始终是赋值,因为初始化仅在您实际声明实例(而不仅仅是指向实例的指针)时发生。
您可以使用 compound literals:
struct sometype *ms = malloc(sizeof *ms);
*ms = ((struct sometype) { .a = 0 });
但当然这可能比只做更糟糕:
ms->a = 0;
因为它将写入结构的 all 字段,将文字中未提及的所有字段设置为零。根据您的需要,这可能会产生不必要的成本。
Well, this does not apply to a struct on heap.
是的。它不会。那是因为初始化和赋值是有区别的。如果
sometype a = {.a =0};
这是初始化。在动态分配的情况下
sometype *a = malloc(sizeof(struct sometype);
*a = {.a =0};
有作业。
显然在 C99 中,您可以用这种方式简单地初始化静态分配的结构
struct sometype {
int a;
double b;
};
sometype a = {
.a = 0;
};
好吧,这不适用于像这样的堆上结构。
struct sometype *a = malloc(sizeof(struct sometype));
*a = {
.a = 0;
};
对于 GCC 4.9.2,编译器有问题
error: expected expression before '{' token
我知道这很愚蠢,但是有什么语法或技术原因我不能这样做吗?
结构初始化和赋值是有区别的。
使用堆内存时,它始终是赋值,因为初始化仅在您实际声明实例(而不仅仅是指向实例的指针)时发生。
您可以使用 compound literals:
struct sometype *ms = malloc(sizeof *ms);
*ms = ((struct sometype) { .a = 0 });
但当然这可能比只做更糟糕:
ms->a = 0;
因为它将写入结构的 all 字段,将文字中未提及的所有字段设置为零。根据您的需要,这可能会产生不必要的成本。
Well, this does not apply to a struct on heap.
是的。它不会。那是因为初始化和赋值是有区别的。如果
sometype a = {.a =0};
这是初始化。在动态分配的情况下
sometype *a = malloc(sizeof(struct sometype);
*a = {.a =0};
有作业。