說我有一些代碼,我有一個變量,我分配一個指針指向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
這可能嗎? (這樣做沒有什麼好的理由 - 只是好奇而已。)
- 編輯:這個問題不是關於指針和引用的區別,而是如何通過使用它們來實現目標,因此不是「引用和指針有什麼區別?」