0

In a common struct , the size of a struct equals the sum of size of all its members, however when I want to apply this for the linked list based on struct ,it does not hold.

I run the following code on a 64-bit windows system, and my complier is gcc

typedef struct node {

    int val;
    struct node *head;
} node_t;

typedef struct point
{
    int x;
    int y;
} point_t ;

int main(){

    point_t a = {1,1};
    node_t b={1,NULL};

    printf("%d %d %d\n",sizeof(node_t),sizeof(b.head),sizeof(b.val));
    printf("%d %d %d",sizeof(point_t),sizeof(a.x),sizeof(a.y));
}

the output turns out to be

16 8 4
8  4 4

what I expect is that sum of sizeof(b.val) and sizeof(b.head) should euqual sizeof(node_t) just as what happens for sizeof(point_t),sizeof(a.x),sizeof(a.y).

so is there anything special of the struct that forms a linked list in the storage?

Rexjz
  • 21
  • 3

1 Answers1

0

hhh I come to answer my own question 5 min later.

reason for this is Data alignment.To take it simplily, in a struct ,storage that equals the size of the largest data will be allocated for each member

In this question,the sizeof(node_t.val) is 4 ,yet 8 is allocated for it(without changing its size) because the largest data type in this struct is struct node*,of which size is 8.

Rexjz
  • 21
  • 3
  • 3
    *"storage that equals the size of the largest data will be allocated for each member"* - that's simply not universally true. According to that logic, adding an `int x;` member *before* member `int val;` in your `struct node` would increase the overall struct side by 8 bytes. Try it. You will likely be surprised. Alignment logic and rules are deeper than you're assuming them to be. – WhozCraig Nov 02 '19 at 05:04