Home > Net >  Pointers to structs in C vs pointers to arrays
Pointers to structs in C vs pointers to arrays

Time:04-25

Do pointers to structures in C work differently 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.

CodePudding user response:

There is no difference. If you want to change the value of the variable you send in to function in such a way that the change is visible in the function that called function, you need to supply its address to function, which is what you do when taking the address of head.

In moidify(array) you send in a pointer to the first element in array which is why modifying the array data works. If you would like to modify the array variable itself (by making it potentially point somewhere else), you would have to take its address too. Example:

void moidify(int **arr) {
    *arr = realloc(*arr, 128);
    if(*arr == NULL) {
        perror(__func__);
        exit(1);
    }
}

int main() {
    int *array = malloc(8);
    *array = 1;
    *(array   1) = 2;
    moidify(&array);
}

CodePudding user response:

You must understand how pointers works to get this one. Here, the variable array is not properly speaking, an array. It's a pointer toward a memory space, of size 8 * sizeof(int). It contains only an address. From this address you can access the values of the array, you move using this address, to the rightfully memory space you want to fill or read.

Once that understood, when you call the moidify function, you are not passing the array. Nor the memory space. You are passing, the address of the memory space. The function gets a copy of the given address, in the argument variable int *arr.

Hence, you can use it the same way you use it from the main function.

If you wanted to change the address toward which the array variable would go, you would need to specify &array to the receiving function, which would then use an int ** argument variable.

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 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 belongs.

  • Related