表示一个地址需要多少内存

How much memory is required to represent an address?

本文关键字:多少 内存 地址 一个 表示      更新时间:2023-10-16

请考虑以下代码。

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(长));