2014-10-05 87 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找出一些其他的變量。