Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need pointers in C implementation of a linked list?

Why is it important to use pointers in an implementation of linked lists in C?

For example:

typedef struct item                                     
{
    type data;
    struct item *next;
} Item;

typedef struct list                                          
    Item *head;
} List;

What would happen if Ill use the same implementation just without the pointers?

like image 964
Joni Avatar asked Jul 16 '13 12:07

Joni


1 Answers

Well you'll end up with something like this

typedef struct item                                     
{
    type data;
    struct item next;
} Item;

and now the C compiler will go to try to figure out how large Item is. But since next is embedded right in Item, it'll end up with an equation like this

size-of-Item = size-of-type + size-of-Item

which is infinite. Hence we have a problem. Because of this, C requires pointers so you have

size-of-Item = size-of-type + size-of-pointer

which is closed. More interestingly, even when you do this in languages like Java, Python, or Haskell, you're really implicitly storing a pointer (they say reference) to break the cycle. They just hide the fact from you.

like image 181
Daniel Gratzer Avatar answered Dec 24 '22 11:12

Daniel Gratzer