-1

I know how the code work. But does not know Why?

What are the differences between pointers?

struct List{
   int val;
   List *next;
}
/// where is the different between fun1 and fun2 receiving the List
void fun1(List **head){}
void fun2(List *head){}
int main(){
    List *head;
     /// where is the different between fun1 and fun2 passing the List
    fun1(&head);
    fun2(head);
}
  • A pointer, is a variable that stores the memory address as its value. So `*head` stores address of the `List`. `**head` stores address of `*head`. – ecoplaneteer Oct 14 '20 at 02:34
  • In the case of `fun1`, the variable `head` is passed by value. In the case of `fun2`, it is passed by reference (using a pointer to the pointer). That way, the function `fun2` has access to the original variable (because it knows its memory address) and is therefore able to change its value, whereas `fun1` cannot change the original variable's value, because it only has a copy of it. Just for clarification: I am using the term "pass by reference" in the general sense. In C++, this term has a slightly different meaning, as it only applies to actual "C++ references", not pointers. – Andreas Wenzel Oct 14 '20 at 02:40

2 Answers2

3

The difference between the two is what memory address you are referencing.

  • fun1(&head);: the memory address you access is the memory address of the head pointer itself.
  • fun2(head);: the memory address you access is where head points to.

Try to output the values of head this way:

void fun1(List **head){
    cout << "Pointer address: " << head << endl;
    cout << "Head points to: " << *head << endl;
}
void fun2(List *head){
    cout << "Head points to: " << head << endl;
}

The output will be something like:

Pointer address: 0x7ffeec04e058
Head points to: 0x104f2a036
Head points to: 0x104f2a036

By using the & operator, you are accessing the memory address of the variable head.

  • I believe the OP may be asking about the difference between "pass by value" and "pass by reference". However, I am not sure. – Andreas Wenzel Oct 14 '20 at 03:01
0

& gets the address of something. In this case that something's a pointer to a List. A pointer simply holds the address of something. So, the address of a pointer to a thing is a pointer to a pointer of that thing.

loremdipso
  • 398
  • 3
  • 8