在结构体内初始化一个数组

3

我有这么一个结构:

typedef struct
{
    union{
        int bytex[8];
        int bytey[7];
   }Value ;
   int cod1;
   int cod;
} test;

我想要初始化常量 test 如下:

const test T{
.Value.bytex = {0x11,0x22,0x33,0x44,0x11,0x22,0x33,0x44},
.cod1=0,
.cod=1,
};

我遇到了以下错误。
Expected primary-expression before '.' token

这个初始化是正确的:
const test T{
{0x11,0x22,0x33,0x44,0x11,0x22,0x33,0x44},
.cod1=0,
.cod=1,
};

你有什么想法吗?

1个回答

4
首先,这与结构体/联合体的初始化语法并不相似。修复方法:
const test T = 
{
  .Value.bytex = { 0x11,0x22,0x33,0x44,0x11,0x22,0x33,0x44 },
  .cod1 = 0,
  .cod  = 1,
};

第二,如果您可以使用标准C语言,则可以省略内部变量名称:
typedef struct
{
  union {
    int bytex[8];
    int bytey[7];
  };
  int cod1;
  int cod;
} test;

const test T = 
{
  .bytex = { 0x11,0x22,0x33,0x44,0x11,0x22,0x33,0x44 },
  .cod1 = 0,
  .cod  = 1,
};

@FiddlingBits 不是的,可能在任何地方。这是C11匿名结构/联合体特性。 - Lundin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接