0
Pointer in C
Hi everyone. I really need some help on understanding pointer. Iāve been encountering this same question over and over in the C challenges and I really donāt get it. Can anybody please help and explain how it works?š„ Hereās the question. ========================== What is the output of the following code? int *p = (int *)malloc(sizeof(int)*4); *p = 42; *(p + 2) = 43; int* v = p; *(v + 1) = 44; printf(ā%dā, p[1]); printf(ā%dā, v[0]);
3 Answers
+ 3
// memory allocation to pointer variable p
int *p = (int*)malloc(sizeof(int)*4);
// set value of address pointer p as 42. it same with p[0]=4
*p = 42;
// same as above but its about p+2 (p[2])
*(p + 2) = 43;
// copy p's address to v. now they points same address.
int* v = p;
// set value of address pointer v+1 as 44. it same with p[1]=44 and v[1]=44
*(v + 1) = 44;
//output section
printf(ā%dā, p[1]);
printf(ā%dā, v[0]);
Hope this helps
+ 1
Mystika L Ohhh now Iām getting it! Thank you so much!!š
0
Jay Matthews thanks Jay š but like I mentioned I really want to know how the code works out! Especially the 4th line:
int* v = p;
what happens here?