2016-12-14 58 views
2

说我有一些代码,我有一个变量,我分配一个指针指向a指针分配完毕后,你能分配一个变量名给指针指向的东西吗?

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

然而,在此之后,我想给这个变量a占据名称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 

这可能吗? (这样做没有什么好的理由 - 只是好奇而已。)

- 编辑:这个问题不是关于指针和引用的区别,而是如何通过使用它们来实现目标,因此不是“引用和指针有什么区别?”

回答

2

我想给存储器位置时变量“a”占据名字“b”

你想要的是参考,如果我正确理解你的问题。

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 
0

不,分配(或重命名)a 变量名称(标识符)是不可能的。

但是,如果你有兴趣,可以随时到

int * b; 
b = &a; 

其中b变量a。对*b进行的更改将反映为a,反之亦然。

0

您可以指向同一个地方多个指针:

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

正如你已经发现了,你不能说&b = ptr;

1

int& b = a结合整数参考ab。变量a的地址完全是未修改。 它只是意味着一个实际使用的所有用途(引用)使用分配给b的值。