[英]Can two pointers use the same address? (Code explanation)
int i1;
int i2;
int *ptr1;
int *ptr2;
i1 = 1;
i2 = 2;
ptr1 = &i1;
ptr2 = ptr1;
*ptr1 = 3;
i2 = *ptr2;
有人可以幫我解釋這段代碼嗎? 特別是第八行,我認為它在pointer2中指定了pointer1的地址,這是否使得指針2指向值1?
請有人幫助我。 謝謝。
ptr2 = ptr1
將ptr1
( i1
的地址)的值賦給ptr2
。 這使得ptr2
指向ptr1
指向的同一個東西,即變量i1
。 ptr2
指向的位置中的值確實是1
,但是說ptr2
指向值1
肯定似乎很奇怪。 ptr2
的值是一個內存位置,該位置當前包含一個位集合(當解釋為int時)表示值1
。
是的,多個指針可以指向同一個位置,這種情況稱為別名 。 雖然你提到的ptr2
線確實使得ptr2
指向值1,但更重要的是它指向i1
的存儲, ptr1
也是如此。 那么在那時你有三個不同的名稱來訪問i1
: *ptr1
, *ptr2
和i1
本身。 因此,最后兩行確實具有順序依賴性,並且程序在i1
和i2
中都以3結束。
int i1; //initialize 2 integers
int i2;
int *ptr1; //initialize 2 pointer to integers
int *ptr2;
i1 = 1; //storing values into the integer variables
i2 = 2;
ptr1 = &i1; //pointer ptr1 pointing to the address of the integer variable i1
ptr2 = ptr1; //pointer ptr2 pointing to the address pointed by ptr1 (perfectly ok)
*ptr1 = 3; //value at the address pointed by ptr1 changed to 3 (which changes the value at the address pointed by ptr2 also
i2 = *ptr2; //value at the address pointed by the ptr2 stored in integer variable i2
你正在做的是在ptr2
的地址中寫入ptr1
的值。 為了形象:在你有一個箭頭ptr1
,說:“如果你需要值1,你可以得到它在那里 ”。 該副本后, ptr2
現在也有,說:“如果你需要值1,你可以得到它在那里 ”的箭頭。 因此,假設ptr2
指向值1
,您確實是正確的。
理解C中的指針就是這樣。
指針基本上是一個變量,其值(R值)是另一個變量的地址(L值)。
變量具有L值(存儲它的存儲器地址)和R值(數據值)。
所以
ptr2 = ptr1;
意味着您要將ptr2的R值分配給ptr1的R值。
Ptr1的R值包含i1的L值,因此:
cout << ptr2; /* print i1's L-value (a memory address) */
cout << *ptr2; /* print 1, that is i1's R-value */
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.