0
Can someone explain this int numb = 15; int *numbptr; numbptr = &numb; *numbptr = 20; cout << *numbptr; Output: 20 why changing the value of the pointer chamge the value of the numb variable too?
5 Respuestas
+ 4
First, we declare an int (numb) with a value of 15.
We then declare an int pointer (numbptr).
We then set numbptr to point to the memory address of numb, so however way we manipulate the pointer, this also affects the int.
We then set pointer numbptr equal to 20, and as stated above, this is setting numb to 20, because numbptr is equal to the memory address of numb.
At this point, if we were to print out *numbptr or numb, they would both return the same result of 20. If we printed out numbptr, it would return the memory address of numb, as a hexidecimal number.
+ 2
For better understanding.
numbptr is the pointer with the memory address. In the line
*numbptr = 20;
the code manipulates the variable (literally the value within the memory address), and not the pointer. The asterisk is the difference:
*numbptr = 20; // manipulates the value in the memory
numbptr = 20; // attempts to manipulate the pointer (possibly compile error, because 20 is not a hex)
+ 2
firstly when we assign a pointer it has address of that particular variable..
but after assigning a value to pointer then pointer takes address of that value by replacing with previous one.....
+ 1
oh yeah thank you guys
+ 1
you set numbptr with address of numb, so if u set *numbptr with any integer value. a value numb will be change to