jsejcksn
jsejcksn

Reputation: 33721

C++ unsized array in struct, error: "too many initializers"

struct led {
  const int loc;
  int state;
  unsigned int stateDuration [];
  int stateMode;
  unsigned long timestamp;
  } led1 = {D0, 0, {500}, 0, 0},
    led2 = {D7, 0, {100, 900, 400}, 0, 0};

This gives me a compilation error "too many initializers" (the array size is 0). Is it possible to declare an unsized array in the structure and then initialize it with varying values like in my example, or must I explicitly declare the array to the maximum size needed?

Upvotes: 1

Views: 640

Answers (2)

tevemadar
tevemadar

Reputation: 13195

You can do it with GCC, using one its C++ language extensions, but only with the very last element of your struct, because the offsets of fields have to be constant.
See: https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html

GCC allows static initialization of flexible array members. This is equivalent to defining a new structure containing the original structure followed by an array of sufficient size to contain the data. E.g. in the following, f1 is constructed as if it were declared like f2.

struct f1 {
  int x; int y[];
} f1 = { 1, { 2, 3, 4 } };

If you are using something else, you can still implement the idea, but only with heap-allocated objects (so the initializer block thing will not be possible) and you will need an own new operator taking care of the dynamic part. (Perhaps delete too, I am not sure)

Upvotes: 2

Brian Bi
Brian Bi

Reputation: 119154

It is illegal to have an array of unknown bound as a non-static member of a struct. [class.mem]/13

Non-static data members shall not have incomplete types.

This is because the size of the class must be known when the closing brace is reached.

Maybe you should make stateDuration a std::vector<unsigned int> instead.

Upvotes: 3

Related Questions