Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dereferencing a double pointer

Tags:

c

I have code snippet that I can't understand how it works, because of one line that does a double dereference. The code looks like this:

void afunction(int**x){
    *x = malloc(2 * sizeof(int));
    **x = 12;
    *(*x + 1) = 13;
}

int main(){
    int *v = 10;
    afunction(&v);

    printf("%d %d\n", v[0], v[1]);
    return 1;
}

I understand that the first element of the pointer to pointer gets the value 12, but the line after that I just can't seem to understand. Does the second element in the first pointer get value 13?

like image 774
Andrei Brașoveanu Avatar asked Feb 05 '23 03:02

Andrei Brașoveanu


1 Answers

The code is rather easy to understand if you use a temporary variable, eg:

void afunction(int**x)
{
    int* t = *x;

    t = malloc(2 * sizeof(int));
    *t = 12;
    *(t+1) = 13;
}

so:

  • x is a pointer to a pointer to int
  • *x yields a int* (pointer to int)
  • **x = is like *(*x) = so you first obtain the pointer to int then by dereferencing you are able to set the value at the address

The last part *(*x+1) = can be broken down:

int* pointerToIntArray = *x;
int* secondElementInArray = pointerToIntArray + 1;
*secondElementInArray = 13;

The purpose of using a pointer to pointer here is that you can pass the address to an int* to the function and let the function allocate the memory and fill it with data. The same purpose could be done by returning an int*, eg:

int* afunction() {
  int* x = malloc(sizeof(int)*2);
  *x = 12;
  *(x+1) = 13;
  return x;
}

int main() {
  int* v = afunction();
  return 0;
}
like image 89
Jack Avatar answered Feb 19 '23 08:02

Jack