Home > Software engineering >  Why declare pointer in linked list?
Why declare pointer in linked list?

Time:06-27

I'm new to C language.

studying linked list, I found it very hard to understand using pointer.

(I understand the benefit of linked list compared to array.)

Let's assume I have 3 customers and specific value to each.

struct linknode{
  int data;
  struct linknode *next
}; 

why we use pointer like (case1)

linknode *a = malloc(sizeof(Node));
linknode *b = malloc(sizeof(Node));
a->value = 1;
b->value = 2;

a->next = b;
b->next = NULL;

How about just (case2)

linknode a, b;
a.value = 1;
b.value = 2;

a.next = &b;
b.next = NULL;

Isn't it possible to make linked list with case 2? also insert, delete being possible?

thanks.

CodePudding user response:

Isn't it possible to make linked list with case 2? also insert, delete being possible?

It is possible, it just isn’t very useful. The maximum size of your list is fixed, and I doubt you’re going to want to declare more than a dozen separate variables.

Something you can do is use an array as your backing store - instead of declaring separate variables a and b you can declare an array of 10, 100, 1000 elements, then do something like:

a[i].next = &a[j];

But you’re still limited - your list can never be bigger than the array. The advantage of using dynamic memory is that the list size isn’t limited; however, it means messing with pointers.

Pointers are a fundamental part of programming in C - you cannot write useful C code without using pointers in some fashion.

CodePudding user response:

Statically-allocated nodes (the latter) is fine, but not very useful in practice.

You'll presumably need to add nodes to your list. And chances are overwhelmingly in favour of some of them needing to be dynamically allocated. For example, nodes created in a loop would need to be dynamically allocated.

If you had a mix of statically- and dynamically-allocated nodes, you won't know which ones to free without some extra flag in each node. This would add complexity of the program. It's easier to only deal with dynamically-allocated nodes than a mix.

  • Related