0

Why show its output 3?? Plz explain

Int x=4; Int *a=&x; x--; *a++; cout<<x;

21st Aug 2020, 8:47 PM
Suparna Podder
Suparna Podder - avatar
8 Antworten
+ 5
https://www.sololearn.com/learn/CPlusPlus/1630/?ref=app int *a = &x; //this line assigning the address of "x" to "a" as the value, so now a is referencing to "x" which mean the value of "a" changes to x's value when "x" is changed. x--; // x now becomes 3 and since "a" points to "x" address, a = 3(a also change) *a++; // This will give garbage value because it increments the pointer, and not the dereferenced value. ------------------------------------------------- check this link https://stackoverflow.com/questions/11754419/incrementing-pointers *ptr++; - increment pointer and dereference old pointer value It's equivalent to: *(ptr_p++) - increment pointer and dereference old pointer value Here is how increment the value (*ptr)++; - increment value That's because ++ has greater precedence than *, but you can control the precedence using () -------------------------------------------------
21st Aug 2020, 9:10 PM
minirkk
minirkk - avatar
+ 3
Well then! you've decremented x to 3: x--; then you wrote the expression: *a++; // is a pointer to x in the line above you used dereference operator along with post-increment operator "obj++". The latter has precedence higher than the dereference operator so: 1- increment the pointer a 2- dereference it. incrementing a here falls in an invalid location in memory because it points now to an invalid location. dereferencing it is an Undefined Behavior.  So the value in the address that 'a' points to is still untouched (3). to achieve what you may wanted use prenthesis to change the precedence order: (*a) ++; now: dereference 'a' first then increment that dereferenced value. so x is 4.
22nd Aug 2020, 11:26 AM
A S Raghuvanshi
A S Raghuvanshi - avatar
+ 2
Suparna Podder I read this wrong
21st Aug 2020, 9:13 PM
Roderick Davis
Roderick Davis - avatar
+ 2
RKK so when we do an operation to *a. a will no longer pointed to x ?
21st Aug 2020, 9:16 PM
Rei
Rei - avatar
+ 1
Thanks RKK
21st Aug 2020, 9:24 PM
Suparna Podder
Suparna Podder - avatar
+ 1
aaaaah yes its make sense now. a just moving sizeof(int) bytes ahead to next memory addess, like an array
21st Aug 2020, 9:24 PM
Rei
Rei - avatar
0
It's a post increment that's why value is not changes. So, how it's show output 3?
21st Aug 2020, 9:08 PM
Suparna Podder
Suparna Podder - avatar
0
It's ok
21st Aug 2020, 9:14 PM
Suparna Podder
Suparna Podder - avatar