I have two structs defined as follows:
struct EmptyStruct{
};
struct StructEmptyArr{
int arr[0];
};
int main(void){
printf("sizeof(EmptyStruct) = %ld\n", sizeof(EmptyStruct));
printf("sizeof(StructEmptyArr) = %ld\n", sizeof(StructEmptyArr));
return 0;
}
Compiled with gcc (g++) 4.8.4 on Ubuntu 14.04, x64.
Output (for both gcc and g++):
sizeof(EmptyStruct) = 1
sizeof(StructEmptyArr) = 0
I can understand why sizeof(EmptyStruct) equals to 1 but cannot understand why sizeof(StructEmptyArr) equals to 0. Why are there differences between two?
StructEmptyArris a syntax error (there must be at least one member in the structure C11 §6.7.2.1 ¶2), as isEmptyStruct(zero size arrays are not permitted in standard C; C11 §6.7.6.2 ¶1). GCC has extensions that may make them acceptable, but the standard says "No".sizeofoperator is a size_t, so you should be using%zuor similar, not%ld.