+ 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
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.
+ 1
replace *p++ to a++;
+ 1
ok got it.. oh it is just because of the operators precedence.. it can also be achieved by writing *p+=1
0
Yep, the *p += 1 would also be more readable when working with pointers.
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☺☺
0
No problem, I did a little edit though so you might want to read again ^^
0
Ok thanks☺