+ 1

Explain this pointer code

I don't understand what this code (from a challenge question) is doing. I am particularly confused by *(p+2) and *(v+1). Could somebody please explain. Thanks in advance int *p = (int*)malloc(sizeof(int)*4; *p = 42; *(p+2) = 43; int* v = p; *(v+1) = 44; printf("%d", p[1]);

20th Mar 2019, 8:38 PM
Heather
Heather - avatar
3 Respostas
+ 2
p is a pointer to an array of 4 integers. *p = 42 is equal to p[0] = 42 *(p + 2) = 43 is equal to p[2] = 43 int *v = p Both p and v point to the same array *(v + 1) = 44 is equal to v[1] = 44 AND p[1] = 44 So p[1] is equal to 44!
20th Mar 2019, 9:03 PM
Théophile
Théophile - avatar
+ 1
Théophile Thanks! Perfect explanation!
20th Mar 2019, 9:27 PM
Heather
Heather - avatar
+ 1
You're welcome!
20th Mar 2019, 9:35 PM
Théophile
Théophile - avatar