samprat
samprat

Reputation: 2214

calculate size of structure that has structure with in it

I have a structure say:

struct sub_struct
{
 short  int  alpha; //2 bytes
 short  int  beta;
 short  int gamma;

}

struct big_struct
{
 char movie;
 char songs;
 short int release;

 sub_struct temp_struct[ 4 ];

}

Somewhere in code I have to check sizeof struct so for that I define in header something like:

const int LEN_BIG_STRUCT = sizeof( big_struct );

Now my question is Will LEN_BIG_STRUCT also include the size of sub_struct or do I need to define size of sub struct as well? if yes then how would I do?

Upvotes: 0

Views: 216

Answers (2)

ctzdev
ctzdev

Reputation: 676

sizeof(x) returns the total amount of bytes by the variable or type x.


In your case:

  • small_struct: 6 bytes total (2 from each short int).
  • big_struct: 2 char and 1 short, as well as an array of small_struct which totals to 24 bytes (4 elements * 6 bytes).

So sizeof(big_struct) returns 28 as the total number of bytes.

To answer your question, you don't need to define the size of small_struct because sizeof() adds all bytes encompassed in the struct like Filip Roséen stated in his answer.


Note: as the comments stated below, 28 bytes for big_struct is not universal on all systems. This is due to data padding in C. You can read a bit about it below:

Upvotes: 1

Filip Roséen
Filip Roséen

Reputation: 63882

Imagine big_struct as a basket, which you have put a smaller basket, sub_struct, inside of.

If you now were to put the big basket, containing the small basket, on a scale; you'd be kinda surprised if the weight didn't include that of the small basket, wouldn't you?

It's a good thing sizeof does the expected..


In other words...

Yes, sizeof yields the total number of bytes that takes part in the object representation of its operand; including any potential padding.


Here's what the C++ Standard says about sizeof:

When applied to a class, the result is the number of bytes in an object of that class including any padding required for placing objects of that type in array.

Note: The operator works the same way in C.


Upvotes: 2

Related Questions