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]);

18th Nov 2018, 5:03 AM
Dora Yumin Lee
Dora Yumin Lee - avatar
3 Antworten
+ 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
18th Nov 2018, 5:35 AM
Mystika L
Mystika L - avatar
+ 1
Mystika L Ohhh now I’m getting it! Thank you so much!!👍
18th Nov 2018, 5:39 AM
Dora Yumin Lee
Dora Yumin Lee - avatar
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?
18th Nov 2018, 5:15 AM
Dora Yumin Lee
Dora Yumin Lee - avatar