Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size of struct with a single element

Tags:

c++

c

Given

struct S {
  SomeType single_element_in_the_struct;
};

Is it always true that

sizeof(struct S) == sizeof(SomeType)

Or it may be implementation dependent?

like image 224
user396672 Avatar asked Aug 27 '10 14:08

user396672


2 Answers

This will usually be the case, but it's not guaranteed.

Any struct may have unnamed padding bytes at the end of the struct, but these are usually used for alignment purposes, which isn't a concern if you only have a single element.

like image 177
James McNellis Avatar answered Sep 24 '22 21:09

James McNellis


It does not have to be equal, due to structure padding.

section 6.7.2.1 in the C99 standard states that "There may be unnamed padding within a structure object, but not at its beginning".

This is refered to as structure padding. Paddings may be added to make sure that the structure is properly aligned in memory. The exakt size of a structure can change if you change the order of its members.

like image 29
Silfverstrom Avatar answered Sep 23 '22 21:09

Silfverstrom