3 ms·
is there a difference between struct{ int something; int someArray[]; } and struct{ int something; int someArray[0]; } ?
by janci 10y ago
is there a difference between
struct{
int something;
int someArray[];
}
and
struct{
int something;
int someArray[0];
}
?
- kazinator 10y agoYes; the latter one is the "flexible array member" which is supported in ISO C99 and later. The former is a constraint violation requiring a diagnostic.
- timmaxw 10y agoDid you mean the other way around? I think someArray[] is a flexible array member and someArray[0] is a constraint violation.
- sigjuice 10y agoYou are right. OP has it backwards. gcc treats someArray[0] almost the same as someArray[]. https://gcc.gnu.org/onlinedocs/gcc-5.1.0/gcc/Zero-Length.html#Zero-Length https://gcc.gnu.org/onlinedocs/gcc-5.1.0/gcc/Zero-Length.htm... Other compilers might have similar treatment for someArray[0].
- tavert 10y agoJust don't try to have both a zero sized array and a flexible array in the same struct. g++ 5 or earlier will compile that, but g++ 6 will not: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69550 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69550
- hughw 10y agoMy C is rusty. I would have thought the former declared a pointer in the second member of the struct, i.e. typically a 4- or 8- byte field. edit: clarifying, I thought int somearray [] was the same as int* somearray.
- TazeTSchnitzel 10y agoI may be wrong, but I think someArray[] only does that for function parameters.
- kazinator 10y agoAlso for external declarations: /* file scope */ int a[]; /* later in same translation unit, or in another one: */ int a[42]; In this case, we get an "incomplete array type" after the first declaration. The storage size isn't known and so sizeof a cannot be computed. This is also a de facto kind of "flexible array", but not formally named such. For instance we can do this: /* In proprietary kernel source code */ /* Size deliberately unspecified */ extern struct driver driver_table[]; The proprietary kernel code is compiled into .o files and linked into a .a archive library. To complete the build, a driver table module must be added and some drivers. The module which defines driver_table can be open-source. It defines the size of driver_table by how many entries there actually are; users can configure as many or few drivers and re-build the kernel, without having to recompile the proprietary part in the .a archive. Unixes were shipped like this once upon a time. The "device major number" is just the position in the device table.
- pklausler 10y agoFormal arguments of array type are transformed into pointers.