Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

size of empty structure in C and C++ [duplicate]

Tags:

c++

c

Sizeof empty struct is 0 byte in C but in C++ it is 1 byte. Why? What's the difference?

like image 923
Ramakrishna Avatar asked Feb 18 '14 11:02

Ramakrishna


People also ask

What is the size of an empty structure in C?

Generally, it is 1 byte.

What is empty structure in C?

In c the behaviour of an empty structure is compiler dependent versus c++ where it is part of the spec (explanations here) C++ A class with an empty sequence of members and base class objects is an empty class.

What is the size of empty class?

The size of an empty class is not zero. It is 1 byte generally. It is nonzero to ensure that the two different objects will have different addresses.

What is the size of structure in C?

The size of the entire structure is 8 bytes. On knowing the structured padding, it is easier to redesign or rewrite the structure.


1 Answers

In C its not correct, you cannot have a struct without a member in it.

C99 says,

If the struct-declaration-list contains no named members, the behavior is undefined.

However GCC allows you to have a no member struct with size being 0. G++ treats struct as if it has a single member of type char in it.

Look at this previous SO answering why in C++ the size is 1B.

like image 129
Sunil Bojanapally Avatar answered Sep 17 '22 22:09

Sunil Bojanapally