Mokus
Mokus

Reputation: 10410

How can I initialize an array of struct with array?

I have the following code but I am having problem to initialize. How can I initialize an array of struct with array?

typedef struct
{
    UINT8_T ID;
    string CN;
} CU_ContractDesc;

typedef struct
{
    UINT8_T DataType;
    UINT8_T DataSize;
    string SignalName; //This used only for debugging
    UINT8_T NrCont;
    CU_ContractDesc Contracts [];
} CU_BusDesc;

CU_BusDesc BusItems[]={
     {SS_SINGLE, sizeof(single_T), "S1", 1, {{99, "GV1"}}},
     {SS_UINT32, sizeof(uint32_T), "S2", 1, {{99, "GV1"}, {1, "GV2"}}}
};

Upvotes: 0

Views: 77

Answers (1)

Alan Birtles
Alan Birtles

Reputation: 36488

If your array size is fixed you must specify its size:

struct CU_BusDesc
{
    UINT8_T DataType;
    UINT8_T DataSize;
    string SignalName; //This used only for debugging
    UINT8_T NrCont;
    CU_ContractDesc Contracts [2];
};

or

struct CU_BusDesc
{
    UINT8_T DataType;
    UINT8_T DataSize;
    string SignalName; //This used only for debugging
    UINT8_T NrCont;
    std::array<CU_ContractDesc, 2> Contracts;
};

CU_BusDesc BusItems[]={
     {SS_SINGLE, sizeof(single_T), "S1", 1, {{{99, "GV1"}}}},
     {SS_UINT32, sizeof(uint32_T), "S2", 1, {{{99, "GV1"}, {1, "GV2"}}}}
};

note that additional braces are required for the std::array initialisation.

If the array isn't a fixed size you should use std::vector, c++ doesn't support structures with arrays with unspecified sizes:

struct CU_BusDesc
{
    UINT8_T DataType;
    UINT8_T DataSize;
    string SignalName; //This used only for debugging
    UINT8_T NrCont;
    std::vector<CU_ContractDesc> Contracts;
};

This will work with your original initialisers.

Upvotes: 3

Related Questions