1

I was researching single linked lists in C and I want to ask why we give as a parameter, for example, in insert function void insert_element(struct Node** head, int element) double pointer, but in display function void display_list(struct Node* head) single pointer to head. They both give the same addresses (we call insert function with &). We use double pointer becouse we modify the list inserting or deleting elements ?

SoLow
  • 137
  • 2
  • 12
  • 1
    The alternative is `struct Node *insert_element(struct Node *head, int element)` which IMO is better. That way, you aren't messing around with pointers-to-pointers, but you do need to assign the return value `head = insert_element(head, x)` – user3386109 May 15 '18 at 22:31
  • Might want to use `const` too in `display_list` to signify the function won't change the *contents* of the list. – MFisherKDX May 15 '18 at 22:34

2 Answers2

5

If the new element becomes the head, you have to modify the head. Just displaying the list, there is no chance the head will change.

Leonard
  • 13,269
  • 9
  • 45
  • 72
0

So when you want to modify basic object, you pass its pointer. So if you want to modify int variable in another function you pass pointer to it. The same is true for pointers, to modify pointers you need pointer to it, otherwise your modifications would be local to the function you called. So in code perspective you have:

void insert_element(struct Node** head, int element) {
    struct Node* newNode;
    *head = newNode;
}

if you have something like this:

void insert_element(struct Node* head, int element) {
    struct Node* newNode;
    head = newNode;
} 

The first would get the address of the head and modify it, the second one would modify head it self and would be local to the insert_element() function.

On the other hand display_element function does not need to modify content of the address all it needs is well pointer to the start.