为什么灵活数组成员的静态初始化有效? [英] Why does static initialization of flexible array member work?

查看:146
本文介绍了为什么灵活数组成员的静态初始化有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为菜单编写了以下基本代码:

I have written the following basic code for a menu:

typedef struct Menu {
    char* title;
    unsigned num_submenus;
    struct Menu *submenu[];
} Menu;

Menu sub1 = {"Submenu 1", 0, {NULL}};
Menu sub2 = {"Submenu 2", 0, {NULL}};
Menu Main = {"Main Menu", 2, {&sub1, &sub2}};   /* No Error?! */

int main()
{
    printf("%s\n", Main.title);
    printf("%s\n", Main.submenu[0]->title);
    printf("%s\n", Main.submenu[1]->title);
}

浏览一些相关问题,似乎使用灵活数组成员的唯一方法是动态为其分配内存.但是,我的编译器非常乐意在没有任何错误或警告的情况下编译和运行代码.这是豆腐吗?

Browsing through a few related questions it seems like the only way to use a flexible array member is to dynamically allocate memory to it. However my compiler is perfectly happy to compile and run the code without any errors or warnings. Is this verboten?

我正在使用MinGW gcc 4.6.1并根据C99规则进行编译.

I am using MinGW gcc 4.6.1 and compiling under C99 rules.

推荐答案

按照C标准,不允许以这种方式初始化柔性数组成员.

Initialization of flexible array member in this way is not allowed as per C standard.

21示例2声明之后:

21 EXAMPLE 2 After the declaration:

struct s { int n; double d[]; };

结构struct s具有灵活的数组成员d. [...]

the structure struct s has a flexible array member d. [...]

22遵循以上声明:

struct s t1 = { 0 }; // valid
struct s t2 = { 1, { 4.2 }}; // invalid
t1.n = 4; // valid
t1.d[0] = 4.2; // might be undefined behavior

t2的初始化无效(并且违反了约束),因为将struct s视为不包含成员d. [...]

The initialization of t2 is invalid (and violates a constraint) because struct s is treated as if it did not contain member d. [...]

但是,GCC允许对灵活数组进行静态初始化:

But, GCC allows the static initialization of flexible array:

相反, GCC允许对灵活数组成员进行静态初始化.这等效于定义一个包含原始结构的新结构,后跟一个足够大的数组来容纳数据.例如.在下面的内容中,f1的构造就像是像f2那样声明.

Instead GCC allows static initialization of flexible array members. This is equivalent to defining a new structure containing the original structure followed by an array of sufficient size to contain the data. E.g. in the following, f1 is constructed as if it were declared like f2.

 struct f1 {
   int x; 
   int y[];
 } f1 = { 1, { 2, 3, 4 } };

 struct f2 {
   struct f1 f1; 
   int data[3];
 } f2 = { { 1 }, { 2, 3, 4 } };

这篇关于为什么灵活数组成员的静态初始化有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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