How much memory is required to represent the address?

Consider the following code snippet.

int var; cout << (long)&var; 

My doubt is how we know that long int is wide enough to hold the memory location indicated by &var . What if this is not enough?

The complete code that 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 that I get:

 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 
+4
source share
2 answers

Not. Perhaps, if this is unlikely, pointers require more storage requirements than any integer. If there is an integer type that is suitable, then for it there will be std::intptr_t (and possibly also std::uintptr_t ) the typedef specified in <cstdint> (only for C ++ 11).

You can check for the presence of intptr_t at the preprocessor stage by checking for the macro definition INTPTR_MAX (or INTPTR_MIN ) after #include <cstdint> .

If you just want to print the pointer value using std::cout , then you can apply it to void* (not necessary for int* , but necessary for char* ) and use << directly without casting to an integer type.

+4
source

You can use assert (or another type of check). Verification must be in the form

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

+3
source

Source: https://habr.com/ru/post/1400826/


All Articles