c - 初始化结构体内部的数组

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

你有什么想法吗?

最佳答案

首先,这与重新组装结构/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,
};

关于c - 初始化结构体内部的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52971866/

相关文章:

c - 如何释放结构中的指针?

c - 为什么此代码会产生 "assignment from incompatible pointertype"警告?

c - C 中的 sizeof() 函数

C 程序 - 如何验证文件中的特定字符串

c++ - 创建邻接表时出现段错误

c - 结构体c简单问题

c++ - 显示结构/类错误数组 C++

c - 忽略 C 中的换行符

c - ARM 上的字对齐?

java - 将 VB.NET 转换为 C、C++ 或 Java