666 views
1 votes
1 votes

as we allocate the space for node in linked list using malloc() so how many bytes malloc allocate for the 1 node i.e. actual value of malloc allocates in ram like i write this code.

so what is size of a node of linked list?

#include<stdio.h>

struct node
{
    int data;
    struct node *link;

};

int main()
{
 struct node *temp;
 temp = (struct node *)malloc(sizeof(struct node));
 printf("%d",sizeof(struct node));
 
    
}

what the printf prints and why ?

 

1 Answer

1 votes
1 votes

Considering the size of pointer variable takes $8$ bytes and size of integer variable $4$ bytes.

Then the answer of $sizeof(struct node)$ would come $16$ .

This is because of padding added to satisfy alignment constraints. Alignment is very much important for performance and optimization of the program.

Here we try to make the structure size multiple of maximum size datatypes Here that is the pointer which is 8 byte.

So We pad 4 byte to int variable .

So now size of structure is $(8+8)=16$ byte  

https://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member

Watch this video :-https://www.youtube.com/watch?v=Kh_zZ85NQ8E&list=PLIPZ2_p3RNHgzQutUHGzqMjA1z7XJ_Uya&index=9

reshown by

Related questions

1 votes
1 votes
1 answer
2
1 votes
1 votes
2 answers
4
srestha asked Sep 11, 2017
1,253 views
1) What is the algorithm for reversing the singly linked list?2) How palindrome could be made with the help of this algo ?