Reputation: 437
I know that in order for a function to write to a parameter, we need to pass a pointer to that parameter. That's also the case if we want to modify a linked list. The thing that I struggle to understand, is that why we need to declare a pointer type P* instead of declaring just the normal type in order to modify the linked list?
What are the main differences between the two examples?
int function(struct list_t** list){
}
int function(struct list_t* list){
}
I can say that in both the examples, I'm passing the pointer to the parameter, which technically allows me to edit the linked list.
Upvotes: 1
Views: 53
Reputation: 409166
With struct list_t* list
then list
is a pointer to a list_t
.
With struct list_t** list
then list
is a pointer to a pointer to a list_t
.
If you have e.g.
list_t* my_list;
then my_list
is a pointer to a list_t
. If you then use the address-of operator &
to get a pointer to my_list
(as in &my_list
) then you get a pointer to a pointer to a list_t
, which is list_t**
.
The use of pointers to pointers is to emulate pass-by-reference in C, which only have pass-by-value. As you say, if you have a pointer to a pointer, then you can dereference it and make it point somewhere else. With a plain pointer, it's passed by value and the value is copied into the argument variable. Modifying a copy will not modify the original.
Upvotes: 2