表示一个地址需要多少内存
How much memory is required to represent an address?
请考虑以下代码。
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
您没有。指针有可能(如果不太可能的话)比任何整数都有更大的存储需求。如果存在合适的整数类型,则在<cstdint>
(仅C++11)中将为其定义一个typedef std::intptr_t
(也可能是std::uintptr_t
)。
您可以在预处理器阶段通过测试宏INTPTR_MAX
(或INTPTR_MIN
)在#include <cstdint>
之后的定义来测试intptr_t
的存在。
如果您只想使用std::cout
打印指针值,则可以强制转换为void*
(int*
不需要,但char*
需要),并直接使用<<
而不强制转换为整数类型。
您可以使用断言(或其他类型的检查)。检查应采用形式
assert(sizeof(&var)<=sizeof(长));
相关文章:
- 必须为 C++20 协程帧保留多少内存?
- 堆栈上的参考用途有多少内存
- 指针数组中将有多少内存分配
- 一个 Excel XLL 插件可以有多少内存?
- 在C 中存储对对象的引用需要多少内存
- 对象指针如何知道要删除多少内存
- 使用犰狳线性代数包存储矩阵需要多少内存
- std::vector-他将分配多少内存(在重新分配期间)
- 一个C++指针使用多少内存
- x64 进程可以在 4GB RAM 上占用多少内存
- 计算出一个程序(规划中)需要多少内存
- C/C++ 程序正在使用多少内存
- 哪些数据结构正在使用多少内存
- 表示一个地址需要多少内存
- 了解我有多少内存可用于一个动态向量c++
- 我怎么能看到我的程序消耗了多少内存
- 在x64中,我们可以通过malloc()获得多少内存
- 是否有一种方法可以测量特定函数从堆栈中消耗了多少内存?
- 在c++中,枚举数据类型消耗多少内存
- 对象消耗了多少内存