Do pointers to structures in C work different than other pointers?
For example in this code:
typedef struct node {
int data;
struct node *next;
} node;
void insert(node **head, int data) {
node *new_node = malloc(sizeof(node));
new_node->data = data;
new_node->next = *head;
*head = new_node;
}
int main() {
node *head = NULL;
insert(&head, 6);
Why do I have to use a pointer to a pointer and can’t use the variable head in the insert function like in this example with arrays:
void moidify(int *arr) {
*arr = 3;
}
int main() {
int *array = malloc(8);
*array = 1;
*(array + 1) = 2;
moidify(array);
}
Here I don’t have to pass &array to the function.
>Solution :
You must understand how pointer works to get this one.
Here, the variable array is not properly speaking, an array. It’s a pointer toward a space memory, of size 8 * sizeof(int). It contains only an address. When you can to access the value from the array, your move using this adress, to the rightfuly memory space you want to fill.
Once that understood, when you call the "moidify" function, you are not passing the array. Nor the memory space. You are passing, the adress of the memory space. The function does a copy of the given address, in the variable int *arr.
Hence, you can use it the same way you use it from the main.
If you wanted to change the address toward which the array variable would go, you would nee to specify &array to the receiving function, which would then use a int ** variable as parameter.
Your example with struct is similar to this last part I just described, you want to change toward which address head is pointing, so, you need to give &head to the function. To get the address of head, and be able to modify the contained address.
You use an address, to access to the memory space called "head", to modify the address inside the memory space called "head", which point toward another memory space, where your struct truly belong.