Part of the problem understanding things like this is terminology. Let’s see if we can clear it up.
A
value is our data. We can name it (with a variable name).
Here we have an object-value — one that is its own entity stored somewhere in memory that we can access uniquely and modify. It currently represents the integer state “-7”.
The
name we have given this unique object-value is “x”.
We can create an
alias — another name — for this value:
Now I have two names I can use to access/modify the object-value: “x”
and “y”.
The technical term for this alias is a
reference.
Before direct references like that were encoded into the C++ language, waaaay back in C, we could create
indirect references, which we call
pointers.
That is, a pointer can be used to obtain a reference to an object-value.
|
int* px; // I am a pointer.
|
A pointer is not itself a reference, or alias — it is its own value. In most cases a pointer is simply the index into a program’s memory of an object-value, which you can obtain with the “address of” operator:
|
int* px = &x; // I am a pointer with value = address in memory of x’s object-value
|
All this memory addressing stuff is actually irrelevant, though. What is important is that a pointer can be used to obtain a direct reference:
|
printf( "an integer value = %d\n", *px );
|
That is, the expression “
*px
” resolves to a
direct reference to the object-value we named “x”.
So in your example you have two value-objects, named “a” and “b” respectively. Easy enough.
Then you create two pointers to them. Still good.
Then you “
dereference” those pointers to obtain direct aliases for the two object-values and perform an assignment.
|
*pa = *pb; // a = b; NOT 10 = 2; *pa ≡ a and *pb ≡ b
|
What is neat about pointers is that you can obtain a reference to things that previously did not have a name.
1 2 3
|
int* xs = new int[ 10 ]; // xs is a pointer to an array of unnamed int-values
*xs = 42; // obtain a reference to the first int-value and assign it a value of ‘42’
*(xs + 1) = 5; // obtain a reference to the second int-value, etc.
|
In C and C++, you can use a fancy syntactic sugar with the
[]
operator:
1 2 3
|
int* xs = new int[ 10 ];
xs[ 0 ] = 42;
xs[ 1 ] = 5;
|
(Don’t forget to
delete[]
stuff you get with
new[]
.)
Hope this helps.