-4
struct abc
{
int x;
char p;
double x;
char x1;
int x2;
char x3;
};

output: sizeof(abc) is 32 byte

but same code

struct abc
    {
    int x;
    char p;
    double x;
    char x1;
    char x3;
    int b3;
    };

output of sizeof(abc) is 24 byte

how in the 1st program compiler taking 8 byte more for a charecter which is defined after integer ?

1 Answers1

1

Compiler adds extra alignment bytes to your structure. In Visual Studio you might compile with undocumented /d1reportAllClassLayout to see this:

1>  class tsp   size(24):
1>      +---
1>   0  | x1
1>   4  | x5
1>   8  | x10
1>  16  | p3
1>      | <alignment member> (size=4)
1>      +---

as you see compiler added additional 4 bytes at the end of structure.

marcinj
  • 48,511
  • 9
  • 79
  • 100
  • but x10 is a pointer variable so its size is 8 byte, so the size of the structure should be 4+4+4+8=20 byte, but how its 24 byte on ubuntu 12.04 – tuhin panda Sep 03 '16 at 11:18
  • @tuhinpanda see here: https://en.wikipedia.org/wiki/Data_structure_alignment#Data_structure_padding its quite nicely explained: "In addition the data structure as a whole may be padded with a final unnamed member. This allows each member of an array of structures to be properly aligned." – marcinj Sep 03 '16 at 11:25