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?
Generally, it is 1 byte.
The size of an empty array is 0, because there are no bytes in it.
An empty structIt occupies zero bytes of storage. As the empty struct consumes zero bytes, it follows that it needs no padding. Thus a struct comprised of empty structs also consumes no storage.
Empty struct in C is undefined behaviour (refer C17 spec, section 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With