您的線路int e = &d - c;
正在減速2 unsigned int *
。
在內存中,&d
是8字節,然後是c
(它取決於您的系統,但我們假設int
是4字節)。實際上,你建立你的籌碼以這樣的方式
unsigned int a = 100; // &a is 0x0
unsigned int &b = a; // &b is 0x0 (it's just an alias)
unsigned int *c = &b; // &c is 0x4
unsigned int d = (unsigned int)(c); // &d is 0x8
的unsigned int
使用內存4個字節。因此,當你在做&d - c
時,它必須返回2
,因爲你正在使用指針運算與unsigned int*
(4 * 2 = 8);所以,當你在做&d - c
時,它必須返回2
。
您可以嘗試使用int e = (short*)&d - (short*)c
結果應爲4
,因爲short
大小爲2(2 * 4 = 8)。
你可以試試int e = (char*)&d - (char*)c
結果應該是8
,因爲char
大小是1(1 * 8 = 8)。
嘗試打印變量和地址瞭解:
#include<iostream>
using namespace std;
int main() {
unsigned int a = 100;
unsigned int &b = a;
unsigned int *c = &b;
unsigned int d = (unsigned int)(c);
int e = (short*)&d - (short*)c;
//int &f = e;
//e ++;
cout << "&a: " << (unsigned int)&a << endl;
cout << "&b: " << (unsigned int)&b << endl;
cout << "&c: " << (unsigned int)&c << endl;
cout << "&d: " << (unsigned int)&d << endl;
cout << endl;
cout << " a: " << a << endl;
cout << " b: " << b << endl;
cout << " c: " << (unsigned int)c << endl;
cout << " d: " << d << endl;
cout << endl;
cout << " e: " << e << endl;
return 0;
}
這裏,int e = (short*)&d - (short*)c;
,結果是:
&a: 3220197356
&b: 3220197356
&c: 3220197360
&d: 3220197364
a: 100
b: 100
c: 3220197356
d: 3220197356
e: 4
減去指向不相關的對象是不確定的行爲。編譯器可以生成任何喜歡的代碼。它確實如此。 – rici
它爲我打印2。 – deepmax
而這並不打印0,對我來說它打印2? – Annabelle