+ 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]);
3 Answers
+ 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!
+ 1
Théophile Thanks! Perfect explanation!
+ 1
You're welcome!