Search code examples
cpointersdereference

Pointer to a pointer dereference


I am learning C language and actually stopped at some maybe obvious problem.

void allocateArray(int **arr, int size, int value) {
    *arr = (int*)malloc(size * sizeof(int));
    if(*arr != NULL) {
        for(int i=0; i<size; i++) {
            *(*arr+i) = value;
        }
    }
}

Caller:

int *vector = NULL;
allocateArray(&vector,5,45);

This is code from Understanding and Using C Pointers. The problem is that I can't imagine how this line works:

*(*arr+i) = value;

to be more precisely, I don't know why we need to use 2 dereferencing stars instead of just writing (*arr+i) = value;

It would be nice to get some better example of how and why it should be like that.


Solution

  • I don't know why we need to use 2 dereferencing stars instead of just writing (*arr+i) = value;

    Since arr is a pointer to a pointer to an int, *arr+1 is a pointer to an int. You need a double pointer so that you could change the vale of the variable from inside a function call.

    The general rule is if you need to change a variable of type sometype inside a function, you need to pass sometype* into the function, and use an additional asterisk inside to make assignments. Otherwise, changes that you make to parameter inside the function will remain local to the function. In this case, sometype is itself a pointer (i.e. int*) so in order to modify it inside allocateArray you need to pass int**.

    Note: in C you do not need to cast malloc, so the second line of code can be rewritten like this:

    *arr = malloc(size * sizeof(int));