我试图在结构体中存储指针和数字数组,但这样做会导致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'
}
我无法理解这个错误,因为它对我来说看起来是正确的。我在做什么错了?
答案 0 :(得分:0)
最近的GCC可为您提供更多有用的诊断信息:
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};
| ^~~~~~~~
假设我们有一个标准的C ++数组:
struct EmitArgs {
const int numbers[5];
const void *src_struct;
};
然后我们仍然对函数有问题,因为当作为函数参数传递时,数组会衰减到指针。我们需要传递参考( void emit(const int (&numbers)[N], const void *s)
)。