2

Possible Duplicate:
Why isn't sizeof for a struct equal to the sum of sizeof of each member?

I can't understand struct mem alloc.

typedef struct a{
} a;

sizeof(a) is 0

typedef struct b{
    int bb
} b;

sizeof(b) is 4

typedef struct b2{
    int *bbbb
} b2;

sizeof(b2) is 8

typedef struct d{
    int x;
    int *y;
} d;

sizeof(d) is 16!

Why sizeof is 16?Is it 12?(int+int point=4+8);

I guess sizeof(int) is 4,if int var in struct,mem is 8?

Community
  • 1
  • 1
SamPeng
  • 177
  • 1
  • 1
  • 9

4 Answers4

4

Why sizeof is 16?Is it 12?(int+int point=4+8);

Since the pointer is 8 bytes wide on your machine, the compiler felt obliged to align it to an 8 byte boundary, for performance reasons. On some architectures it may not even be strictly a performance problem: unaligned access to certain types can be outright illegal.

In other words the compiler is allowed to add padding everywhere, except before the first element of the structure.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
1

Depending on what platform you are on, sizeof(int *) could be 4 or 8 (or other). Also, your compiler has the freedom to add unused padding bytes to the struct if it wants to.

David Grayson
  • 84,103
  • 24
  • 152
  • 189
0

This is due to padding and memory alignment. Refer to this link for further explanations.

Deepanjan Mazumdar
  • 1,447
  • 3
  • 13
  • 20
0

Memory aligment is at work. Things need to be aligned.

Ed Heal
  • 59,252
  • 17
  • 87
  • 127