为什么我不能使用部分结构初始化在C malloced结构 [英] why can't I use partial struct initialization for a malloced struct in C

查看:830
本文介绍了为什么我不能使用部分结构初始化在C malloced结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Apperently C99可以简单地用这种方式初始化静态分配结构

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;
 };

使用GCC 4.9.2,编译器抱怨

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).

您可以使用复合文字

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.

这篇关于为什么我不能使用部分结构初始化在C malloced结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆