0

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"}}}
};
6
  • Corrected, it is CPP. Commented Mar 6, 2020 at 9:48
  • 5
    Plain arrays in C++ are dumb: CU_ContractDesc Contracts[]; has to have a fixed size (e.g. CU_ContractDesc Contracts[4];). Since that is probably not what you want, use std::vector<CU_ContractDesc> Contracts; instead. Commented Mar 6, 2020 at 9:51
  • It would be useful to know how the different types are defined. Commented Mar 6, 2020 at 9:51
  • AFAIR, c++ does not allow member variables with incomplete type, not even at the end of a struct. Commented Mar 6, 2020 at 10:01
  • Since when did C++ start using typedef for struct? Commented Mar 6, 2020 at 10:08

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.