【问题标题】:Initialize an array inside a structure初始化结构内的数组
【发布时间】:2018-10-24 14:44:22
【问题描述】:

我有这个结构:

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

你有什么想法吗?

【问题讨论】:

    标签: c struct


    【解决方案1】:

    首先,这与结构/联合初始化语法并不接近。修复:

    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 匿名结构/联合功能。
    猜你喜欢
    • 1970-01-01
    • 2014-10-07
    • 2015-07-29
    • 1970-01-01
    • 2013-09-10
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 2015-04-13
    相关资源
    最近更新 更多