Question

Given the following code:

struct BufferPair
{
    ByteBuffer _a;
    ByteBuffer _b;

    bool _c;
};

struct TestData
{
    MyClass _myClass;

    BufferPair _data[];
};

I'm trying to initialize an array of TestData where I also initialize an array of BufferPair. Each instance of TestData will have a differently sized BufferPair array. Simplified Example:

const TestData g_Data[] = { MyClass(), { { bufOne, bufTwo, someBool }, { bufThree, bufFour, anotherBool } } };

While trying this, I get the following gcc error:

error: too many initializers for 'BufferPair [0]'.

How would I solve this? Thanks.

Was it helpful?

Solution

struct TestData
{
    MyClass _myClass;
    BufferPair _data[];
};

_data in the code above is not a complete type (it is lacking the size of the array), and you are not allowed to declare a member to be of incomplete type in the C++ standard:

9.2p10

Non-static (9.4) data members shall not have incomplete types.

This seems to compile as an extension to the language in gcc. Now it still fails to compile the definition of the variable as the array has no size and you are trying to initialize members in it.

OTHER TIPS

You didn't write the size of the array BufferPair[] - it's zero, so you can't fill it with values.

Try BufferPair[2] and see if this solves the problem.

You cannot initialize an array without a length, as said in the other answers. The only way to do this is initializing the struct at runtime using the "Length 1 trick" (or length 0 trick if you're using gcc).

See this post for more information on how to do that Allocating struct with variable length array member

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top