5

我正在尝试在声明时初始化以下联合数组:

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]’)
4

3 回答 3

14

引用此页面

使用 C89 风格的初始化器,必须按照声明的顺序初始化结构成员,并且只能初始化联合的第一个成员。

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

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

重要的是.f

于 2012-07-19T10:06:13.200 回答
3

您需要指出您正在初始化哪个联合字段。尝试使用以下语法:

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

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

于 2012-07-19T10:07:15.740 回答
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} } };

如果您在没有成员规范的情况下初始化联合,例如 .f = { ... },则联合的第一个成员被初始化。

于 2012-07-19T11:58:46.070 回答