0
Why show its output 3?? Plz explain
Int x=4; Int *a=&x; x--; *a++; cout<<x;
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 ()
-------------------------------------------------
+ 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.
+ 2
Suparna Podder I read this wrong
+ 2
RKK so when we do an operation to *a. a will no longer pointed to x ?
+ 1
Thanks RKK
+ 1
aaaaah yes its make sense now.
a just moving sizeof(int) bytes ahead to next memory addess, like an array
0
It's a post increment that's why value is not changes. So, how it's show output 3?
0
It's ok