2

Say I have some code where I have a variable a and I allocate a pointer to point to a:

int a = 5;
int* ptr = &a;

However, after this, I want to give the memory location that variable a occupies the name b.

int b = a;  // doesn't work, because it only copies the value
&b = ptr;   // doesn't work, not an assignable value

ptr = &b;   // doesn't work, this moves the pointer to point to b
            // instead of renaming the location that ptr already pointed to

Is this possible? (There's no good reason for doing this - just curious.)

-- Edit: This question is not about the differences between pointers and references, but rather how to achieve a goal through using them, and thus is not a duplicate of "what is the difference between references and pointers?"

user2009020
  • 287
  • 1
  • 3
  • 10

4 Answers4

2

I want to give the memory location that variable "a" occupies the name "b"

What you want is reference, if I understand your question correctly.

int& b = a;       // b is an alias of a
assert(&a == &b); // the same memory location

b = 6;            // the value of both a and b changed to 6
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
1

int& b = a binds the integer reference a to b. The address of the variable a is completely unmodified. It simply means that all uses (references) of a actually use the value assigned to b.

msc
  • 33,420
  • 29
  • 119
  • 214
0

No, assigning (or renaming) a variable name (identifier) is not possible.

However, if you're interested, you can always to

int * b;
b = &a;

where b points to the variable a. Changes made to *b will reflect to a and vice-versa.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

You can have multiple pointers pointing to the same place:

int i = 10;
int* p1 = &i;
int* p2 = &i;
int* p3 = p2;

As you have already discovered, you cant say &b = ptr;

John3136
  • 28,809
  • 4
  • 51
  • 69