在结构内部初始化数组

时间:2018-10-24 14:44:22

标签: c struct

我有这样的结构:

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 个答案:

答案 0 :(得分:4)

首先,这与组装struct / union初始化语法不太接近。修复:

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,
};