Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pointer to struct in C vs pointer to array

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading