2014-10-05 89 views
0

在C++中,我怎么能修改变量的指针,e.g:修改变量的地址?

int x = 5;//holds 5 
int y = 10;//holds 10 
int *y_ptr = &y;//holds the address where 10 is stored 

&x = y_ptr;//I want the address of x to be the same as the address of y 

在最后一行我得到一个编译器错误,我在做什么错?

+0

在一个地址中不能有两个变量。 – chris 2014-10-05 21:13:10

+0

变量的地址是只读的,你不能改变它。 – saadtaame 2014-10-05 21:13:13

+0

@mpromonet:它应该用任何OP有问题的语言标记,在这种情况下显然是C++。 – 2014-10-05 21:19:28

回答

3

这是不可能的。变量有一个固定的地址。

你必须有两个标识做参考同一个变量:

int x = 5; 
int &y = x; 

,但你不能在以后更改y找出一些其他的变量。