Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between sizeof(empty struct) and sizeof(struct with empty array)?

Tags:

c++

c

struct

sizeof

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?

like image 880
duong_dajgja Avatar asked Jul 19 '17 15:07

duong_dajgja


People also ask

What is the size of an empty struct?

Generally, it is 1 byte.

What is empty array size?

The size of an empty array is 0, because there are no bytes in it.

Can you have an empty struct?

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.

What is the use of empty structure in C?

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.


1 Answers

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.

like image 63
haccks Avatar answered Oct 12 '22 01:10

haccks