Dereferencing a double pointer

北慕城南 提交于 2021-02-18 08:03:06

问题


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?


回答1:


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;
}


来源:https://stackoverflow.com/questions/42118190/dereferencing-a-double-pointer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!