+ 2

Hi! I code this and output is : 2686748 5 why? I think it should be : 6 6, and when I use +=1 instead the output is6 6

https://code.sololearn.com/c1wCZ4QXM2s7/?ref=app

23rd Jul 2017, 9:43 AM
ghazal minaee
7 ответов
+ 2
Sure, replacing *p++ by a++ works, but that's not really the point of the question. *p++ is not really doing what you think it is. It first returns the value pointed at by the pointer, then it increments the address of the pointer due to operator precedence. So now you end up with a pointer thats not pointing to a anymore and you end up with garbage. Use (*p)++ instead, this makes sure the pointer is first dereferenced and then the value at that address is incremented. Note that ++*p; would increment the value at the pointer first as you would expect, so I don't really recommend using ++ together with a pointer because it gets confusing really quickly.
23rd Jul 2017, 10:30 AM
Dennis
Dennis - avatar
+ 1
replace *p++ to a++;
23rd Jul 2017, 9:58 AM
Мг. Кнап🌠
Мг. Кнап🌠 - avatar
+ 1
ok got it.. oh it is just because of the operators precedence.. it can also be achieved by writing *p+=1
23rd Jul 2017, 10:20 AM
Мг. Кнап🌠
Мг. Кнап🌠 - avatar
0
Yep, the *p += 1 would also be more readable when working with pointers.
23rd Jul 2017, 10:22 AM
Dennis
Dennis - avatar
0
Thank you so much Dennis😊 I know it will work with +=1 , I just wanted to know why this happens Sami khan but thanks☺☺
23rd Jul 2017, 10:30 AM
ghazal minaee
0
No problem, I did a little edit though so you might want to read again ^^
23rd Jul 2017, 10:31 AM
Dennis
Dennis - avatar
0
Ok thanks☺
23rd Jul 2017, 10:32 AM
ghazal minaee