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?

25th Aug 2016, 1:02 AM
Carlos Augusto Silva Gurgel
Carlos Augusto Silva Gurgel - avatar
5 Réponses
+ 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.
25th Aug 2016, 2:59 AM
Cohen Creber
Cohen Creber - avatar
+ 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)
26th Aug 2016, 5:17 AM
Tamas Szekffy
Tamas Szekffy - avatar
+ 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.....
27th Aug 2016, 6:42 PM
ABHISHEK GOEL
ABHISHEK GOEL - avatar
+ 1
oh yeah thank you guys
26th Aug 2016, 9:57 PM
Carlos Augusto Silva Gurgel
Carlos Augusto Silva Gurgel - avatar
+ 1
you set numbptr with address of numb, so if u set *numbptr with any integer value. a value numb will be change to
27th Aug 2016, 6:11 AM
fajr