what is the output of the snippet code and how?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

what is the output of the snippet code and how??

int arr[]={1,2,3,4,5}; int *p=arr; ++*p; p+=2; printf("%d",*p);

3rd Jan 2022, 3:32 PM
Nariman Tajari
Nariman Tajari - avatar
4 Answers
+ 3
int *p = arr; Now p points to the beginning or the 1st element in the array which is 1. ++*p; *p means the value at address pointed by p and ++*p means incrementing the value at p by 1. So the value 1 at p is incremented by 1. You can check this by printing arr[0]. p+=2; This means that the address pointed by p should be incremented by 2 places. Now the pointer sits on the 3rd element in the array which is 3. printf("%d",*p); It now prints the value at address pointed by p which is 3.
3rd Jan 2022, 4:11 PM
Avinesh
Avinesh - avatar
+ 1
There is a difference between just p and *p. The *p will give you the value at p. So any operation like ++*p will change the value at p. Whereas just p will give you the address of the value pointed by p. Any operation on p like p+=2 will increment the address and not the value itself.
3rd Jan 2022, 5:04 PM
Avinesh
Avinesh - avatar
0
shouldnt we give the value of p after level ++*p equal to 2, and after that by p+=2 it would be 4? i became q little bit confused in the second paragraph of your statement Avinesh
3rd Jan 2022, 4:37 PM
Nariman Tajari
Nariman Tajari - avatar
0
i guess you mean that p+=2 term is just affect on *p not on *p++
3rd Jan 2022, 5:00 PM
Nariman Tajari
Nariman Tajari - avatar