@ science man
because you're sending "firstvalue" and "secondvalue" directly to cout
if you replaced these lines:
1 2
|
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
|
with these:
1 2
|
cout << "firstvalue is " << *mypointer << endl;
cout << "secondvalue is " << *mypointer << endl;
|
you'd get only the value of "secondvalue" because a reference to it is assigned to "mypointer" in line 11 above. It no longer points to "firstvalue" at this time.
To hold two references you need two pointers, like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
#include <iostream>
using namespace std;
int main ()
{
int firstvalue, secondvalue;
int * mypointer_1, mypointer_2;
mypointer_1 = &firstvalue;
*mypointer_1 = 10;
mypointer_2 = &secondvalue;
*mypointer_2 = 20;
cout << "firstvalue is " << *mypointer_1 << endl;
cout << "secondvalue is " << *mypointer_2 << endl;
return 0;
}
|
ta da!
also:
All this I'm on board with because to me I'm thinking that both variable names are being assigned to the same numerical value.
|
Don't think for a second that a pointer has anything to do with the actual "name" of a variable, nor is it a numerical value in the sense that "int" is. You can change the reference a pointer points to (unless you declare it as const) ... actually I think that's kind of the point of the original code up top there, to show you that you
can change a pointer's reference.
Just to say it again, the pointer references only one variable at a time in that program. When "mypointer" points to "firstvalue", 10 is assigned to the integer which "mypointer" points to, which is "firstvalue".
1 2
|
mypointer = &firstvalue;
*mypointer = 10;
|
Then a reference to secondvalue, "&secondvalue", is assigned to mypointer. then a value of 20 is assigned to the integer which mypointer points to NOW which is "secondvalue".
1 2
|
mypointer = &secondvalue;
*mypointer = 20;
|
..it's just like making two assignments to any variable:
1 2 3
|
int quant;
quant = 10;
quant = 20;
|
At no point would "quant" hold two values, the second assignment causes the value 10 to be "forgotten."