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?
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 addressThe 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With