您的线路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