考虑下面这段代码。
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
答案 0 :(得分:4)
你没有。对于具有比任何整数更大的存储要求的指针,它是可能的 - 如果不可能的话。如果有一个合适的整数类型,那么std::intptr_t
中定义的std::uintptr_t
(也可能是<cstdint>
)将有一个typedef(仅限C ++ 11)。
您可以通过在intptr_t
之后测试宏INTPTR_MAX
(或INTPTR_MIN
)的定义来测试预处理器阶段是否存在#include <cstdint>
。
如果您只想使用std::cout
打印指针值,则可以转换为void*
(int*
不必要但char*
必需)并使用{{1}直接没有强制转换为整数类型。
答案 1 :(得分:3)
您可以使用断言(或其他类型的检查)。 检查应采用
格式断言(sizeof(&amp; var)&lt; = sizeof(long));