Reputation: 4276
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?
Upvotes: 35
Views: 3232
Reputation: 106012
In C, the behavior of a program is undefined if a struct is defined without any named member.
C11-§6.7.2.1:
If the struct-declaration-list does not contain any named members, either directly or via an anonymous structure or anonymous union, the behavior is undefined.
GCC allows an empty struct as an extension and its size will be 0
.
For C++, the standard doesn't allow an object of size 0
and therefore sizof(EmptyStruct)
returns a value of 1.
Arrays of zero length are not supported by standard C++¹, but are supported as an extension by GNU and the sizeof
operator will return 0
if applied.
1. § 8.5.1-footnote 107) C++ does not have zero length arrays.
Upvotes: 40
Reputation:
https://gcc.gnu.org/onlinedocs/gcc/Empty-Structures.html
G++ treats empty structures as if they had a single member of type char.
https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html
Zero-length arrays are allowed in GNU C. They are very useful as the last element of a structure that is really a header for a variable-length object.
Upvotes: 5