-3

In a structure of node size of data is 4 bytes and the size of node* is 8 bytes while the size of node is 16 bytes. After 4+8=12 where is 4 extra bytes of node?

I do not understand anything about this.

struct node
{
    int data;
    struct node* next;
}s;
int main()
{
     printf("node => %d \n",sizeof(s));
     printf("node.data => %d \n",sizeof(s.data));
     printf("node* => %d ",sizeof(s.next));
 return 0;
 }
 /*OUTPUT- 
 node => 16 
 node.data => 4
 node* => 8 */
  • 5
    What you see there is a practical example of [data structure alignment](https://en.wikipedia.org/wiki/Data_structure_alignment) The Wikipedia article must suffice, –  Jul 06 '19 at 21:08
  • If you're looking for a solution in C, why is this tagged C# and C++? Please only use the relevant tags. – 41686d6564 stands w. Palestine Jul 06 '19 at 21:29
  • Look up "structure padding" for an explanation of why the size of a struct can be more than the sum of sizes of its members. Also, printing the result of the `sizeof` operator using `%d` gives undefined behaviour, since `%d` specifies an `int` and `sizeof` does not give a result of type `int`. – Peter Jul 07 '19 at 05:45

1 Answers1

0

From this documentation (https://en.cppreference.com/w/c/language/struct) There may be unnamed padding between any two members of a struct or after the last member, but not before the first member. The size of a struct is at least as large as the sum of the sizes of its members.

This is due to alignment requirements.

    |--|--|--|--|??|??|??|??|--|--|--|--|--|--|--|--|
    int         padding     pointer

The pointer is aligned on a multiple of 8 on your platform.
(https://en.wikipedia.org/wiki/Data_structure_alignment)

prog-fh
  • 13,492
  • 1
  • 15
  • 30