考虑以下代码。
int var;
cout << (long)&var;
我的疑问是我们如何知道 long int 有足够的宽度来保存 &var
指示的内存位置。如果不够怎么办?
我正在执行的完整代码...
//: C03:YourPets2.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
#include <iostream>
using namespace std;
int dog, cat, bird, fish;
void f(int pet) {
cout << "pet id number: " << pet << endl;
}
int main() {
int i, j, k;
cout << "Address size " << sizeof(&f) << endl;
cout << "Long size " << sizeof(long) << endl;
cout << "Intptr size " << sizeof(intptr_t) << endl;
cout << "f(): " << &f << endl;
cout << "f(): " << (long)&f << endl;
cout << "f(): " << (long long)&f << endl;
cout << "dog: " << (long)&dog << endl;
cout << "cat: " << &cat << endl;
cout << "bird: " << &bird << endl;
cout << "fish: " << (long)&fish << endl;
cout << "i: " << (long)&i << endl;
cout << "i: " << (long long)&i << endl;
cout << "j: " << (long)&j << endl;
cout << "k: " << (long)&k << endl;
} ///:~
我得到的结果:
Address size 4
Long size 4
Intptr size 4
f(): 1
f(): 134514548
f(): 134514548
dog: 134521044
cat: 0x804a0d8
bird: 0x804a0dc
fish: 134521056
i: -1074729380
i: -1074729380
j: -1074729384
k: -1074729388
最佳答案
你不知道。指针有可能(如果不太可能)具有比任何整数都更大的存储要求。如果有一个合适的整数类型,那么就会有一个类型定义 std::intptr_t
(也可能是 std::uintptr_t
)在 <cstdint>
中定义(仅限 C++11)。
您可以测试 intptr_t
是否存在在预处理器阶段通过测试宏的定义 INTPTR_MAX
(或 INTPTR_MIN
)在 #include <cstdint>
之后.
如果您只想使用 std::cout
打印指针值然后你可以转换为 void*
(对于 int*
是不必要的,但对于 char*
是必需的)并使用 <<
直接转换为整数类型。
关于c++ - 表示一个地址需要多少内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9654914/