在声明时初始化一个union数组

时间:2012-07-19 10:01:45

标签: c arrays sse initializer unions

我正在尝试在声明中初始化以下union数组:

typedef union { __m128d m;  float f[4]; } mat;
mat m[2] = { {{30467.14153,5910.1427,15846.23837,7271.22705},
{30467.14153,5910.1427,15846.23837,7271.22705}}};

但是我发现了以下错误:

matrix.c: In function ‘main’:
matrix.c:21: error: incompatible types in initialization
matrix.c:21: warning: excess elements in union initializer
matrix.c:21: warning: (near initialization for ‘m[0]’)
matrix.c:21: warning: excess elements in union initializer
matrix.c:21: warning: (near initialization for ‘m[0]’)
matrix.c:21: warning: excess elements in union initializer
matrix.c:21: warning: (near initialization for ‘m[0]’)
matrix.c:21: error: incompatible types in initialization
matrix.c:21: warning: excess elements in union initializer
matrix.c:21: warning: (near initialization for ‘m[1]’)
matrix.c:21: warning: excess elements in union initializer
matrix.c:21: warning: (near initialization for ‘m[1]’)
matrix.c:21: warning: excess elements in union initializer
matrix.c:21: warning: (near initialization for ‘m[1]’)

3 个答案:

答案 0 :(得分:11)

引用this page

  

使用C89样式的初始值设定项,必须按声明的顺序初始化结构成员,并且只能初始化union的第一个成员。

因此,要么先放置float数组,要么尽可能使用C99并写:

mat m[2] = { { .f = { /* and so on */ } }, /* ... */ };

重要的是.f

答案 1 :(得分:2)

您需要指明要初始化的联合字段。尝试使用以下语法:

mat m[2] = {
    {.f = {30467.14153,5910.1427,15846.23837,7271.22705}},
    {.f = {30467.14153,5910.1427,15846.23837,7271.22705}}
};

这为我成功编译,没有任何警告。

答案 2 :(得分:0)

尝试更改成员:

typedef union {
    float f[4];
    __m128d m;
} mat;
mat m[2] = { { {30467.14153,5910.1427,15846.23837,7271.22705},
               {30467.14153,5910.1427,15846.23837,7271.22705} } };

如果在没有成员规范的情况下初始化union,如.f = {...},那么初始化第一个union成员。