Sam Denty
Sam Denty

Reputation: 4085

C++ too many initializers for struct

I'm attempting to store a pointer and array of numbers inside a struct, but doing so results in too many initializers.

struct EmitArgs {
  const int numbers[];
  const void *src_struct;
};

void emit(const int numbers[], const void *src_struct) {
  EmitArgs emitArgs = {numbers, src_struct};
                            // ^^^^^^^^^^ too many initializers for 'EmitArgs'
}

I can't make sense of this error, as it looks correct to me. What am I doing wrong?

Upvotes: 2

Views: 1099

Answers (1)

Toby Speight
Toby Speight

Reputation: 30817

Recent GCC gives you more helpful diagnostics:

54192410.cpp:2:13: warning: ISO C++ forbids flexible array member ‘numbers’ [-Wpedantic]
    2 |   const int numbers[];
      |             ^~~~~~~
54192410.cpp:2:13: error: flexible array member ‘EmitArgs::numbers’ not at end of ‘struct EmitArgs’
54192410.cpp: In function ‘void emit(const int*, const void*)’:
54192410.cpp:7:43: error: non-static initialization of a flexible array member
    7 |   EmitArgs emitArgs = {numbers, src_struct};
      |                                           ^
54192410.cpp:7:43: warning: missing initializer for member ‘EmitArgs::src_struct’ [-Wmissing-field-initializers]
54192410.cpp:7:12: warning: unused variable ‘emitArgs’ [-Wunused-variable]
    7 |   EmitArgs emitArgs = {numbers, src_struct};
      |            ^~~~~~~~

Suppose we had a standard C++ array:

struct EmitArgs {
  const int numbers[5];
  const void *src_struct;
};

Then we'd still have a problem with the function, as arrays decay to pointers when passed as function arguments. We'd need to pass a reference instead (void emit(const int (&numbers)[N], const void *s)).

Upvotes: 1

Related Questions