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

前端之家收集整理的这篇文章主要介绍了在声明时初始化一个union数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试在声明时初始化以下union数组:
typedef union { __m128d m;  float f[4]; } mat;
mat m[2] = { {{30467.14153,5910.1427,15846.23837,7271.22705},{30467.14153,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]’)

解决方法

引用 this page

With C89-style initializers,structure members must be initialized in the order declared,and only the first member of a union can be initialized.

所以,要么先将float数组放入,要么尽可能使用C99并写入:

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

重要的是.f.

猜你在找的C&C++相关文章