-1

I have the following code:

#include<stdio.h>
typedef struct _node_1
{
    int number;
    int scores;
    int xyz;
    double p; 
} Node_1;

typedef struct _node_2
{
    int number;
    int scores;
    int xyz;
    struct _node_2 *p; 
} Node_2;

typedef struct _node_3
{
    int number;
    int scores;
    int xyz;
    struct _node_2 p; 
} Node_3;
int main()
{
    printf("%d\n",sizeof(Node_1));
    printf("%d\n",sizeof(Node_2));
    printf("%d",sizeof(Node_3));
    return 0;
}

and the output is:

24
24
40

My question is why the result of these 3 examples's outputs are like this and how do we exactly determine the size of a structure? BTW, my operating system is 64-bit. Thank you!

Jiaming Huang
  • 101
  • 1
  • 6
  • and note that sizes must be printed using [`%zu`](http://stackoverflow.com/q/940087/995714) – phuclv Dec 10 '16 at 17:42

1 Answers1

2

For the first & second one, you would expect 4+4+4+8 = 20 because of the size of the internal data, but you forgot about alignment.

64-bit pointers & doubles (64 bit) too need to be aligned to 8-byte boundary. The compiler inserts a 4-byte padding for this.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219