Mouin
Mouin

Reputation: 1103

Initialize an array inside a structure

I have this structure:

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

and want to initialize the constant test as follow:

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

I am getting the following error

Expected primary-expression before '.' token

This initialization is however correct:

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

Do you have any Idea ?

Upvotes: 3

Views: 91

Answers (1)

Lundin
Lundin

Reputation: 215115

First of all, this isn't close to ressembling struct/union initialization syntax. Fix:

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

Second, if you have the option to use standard C, you can drop the inner variable name:

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

Upvotes: 4

Related Questions