简体   繁体   English

表示地址需要多少内存?

[英]How much memory is required to represent an address?

Consider the following piece of code. 考虑以下代码。

int var;

cout << (long)&var;

My doubt is how do we know that long int has sufficient width to hold the memory location indicated by &var . 我怀疑的是我们怎么知道long int有足够的宽度来保存&var指示的内存位置。 What if it is not sufficient? 如果还不够怎么办?

The full code which I am executing... 我正在执行的完整代码......

//: 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;
} ///:~

The result which I am getting: 我得到的结果:

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

You don't. 你没有。 It's possible - if unlikely - for pointers to have larger storage requirements than any integer. 对于具有比任何整数更大的存储要求的指针,它是可能的 - 如果不可能的话。 If there is an integer type that is suitable then there will be a typedef for it std::intptr_t (and possible also std::uintptr_t ) defined in <cstdint> (C++11 only). 如果有一个合适的整数类型,那么在<cstdint>定义的std::intptr_t (以及可能的std::uintptr_t )将有一个typedef(仅限C ++ 11)。

You can test for the presence of intptr_t at the preprocessor stage by testing for the definedness of the macro INTPTR_MAX (or INTPTR_MIN ) after #include <cstdint> . 您可以通过在#include <cstdint>之后测试宏INTPTR_MAX (或INTPTR_MIN )的定义性来测试预处理器阶段是否存在intptr_t

If you just want to print a pointer value using std::cout then you can cast to void* (unnecessary for int* but necessary for char* ) and use << directly without a cast to an integer type. 如果你只想使用std::cout打印一个指针值,那么你可以转换为void*int*必需的,但char*必需的)并且直接使用<<而不使用强制转换为整数类型。

You can use an assert (or a different kind of check). 您可以使用断言(或不同类型的检查)。 The check should be in the form 检查应该在表格中

assert( sizeof( &var ) <= sizeof(long) ); assert(sizeof(&var)<= sizeof(long));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM