Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size of a linked list node

I find this thing a little tricky and recursive as to how sizeof operator calculates the size of one node in a linked list. I've the below structure as one node in list for example:

struct ll_core
{
    char c_ll;
    struct ll_core * next;
};

printf("size of struct ll_core = %d\n\n",sizeof(struct ll_core));

it gives me an answer 8. Now how does it decides the size 8, because to add sizes of individual struct element it agains encounter the same struct ll_core. So it's a kind of loop or recursion while calculating size. Please excuse me and let me know if I'm missing any basic thing in my head while thinking like this.

like image 609
Diwakar Sharma Avatar asked May 25 '26 03:05

Diwakar Sharma


2 Answers

It doesn't need the size of the struct again, since the struct only contains a pointer to the struct, not the struct itself.

The size of "pointer to struct ll_core" has nothing to do with size of struct ll_core, they are two distinct types. One is pointer, the other one isn't.

You can't declare a "truly" recursive data structure, since it would be infinite.

like image 72
unwind Avatar answered May 26 '26 15:05

unwind


Assuming you are running your code on 32 bit machine, size of pointer will be 4 bytes. As structure will be aligned on word boundary, 3 bytes will be padded and so the size will be 8 bytes.

this structure will actually be like,

struct ll_core{
    char       c_11:
    char const byte[3];  //padded bytes for alignment reasons
    struct ll_core *next;
};
like image 26
nurd_droid Avatar answered May 26 '26 16:05

nurd_droid