Pointer in C | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
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 Respostas
+ 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