I was looking for information on this issue, but I did not find a definite answer. Someone says that everything depends on the bitness of the operating system: if the system is x64, then 8 bytes are allocated, if x86, then 4. Others claim that the pointer takes up as much memory as the variable pointed to by the pointer. That is, if I have a string variable of type string, which takes 28 bytes, then if I create a pointer to this variable, then it will take 28 bytes? Or 4 (8)? Where is the correct information?
2 answers
The size of the pointer depends on the compiler settings at the time of compiling the program. Nothing more. As you say to the compiler, so be it. No relation to the OS or hardware on which the program is compiled, the size of the pointer does not have. Compiler settings determine all parameters of the target platform for which the compilation will be performed, including the pointer size.
Modern “mass” target platforms use the so-called flat memory model with pointers of 32 or 64 bits (4 or 8 bytes). During DOS / Win16, when the underlying hardware used memory segment addressing, C ++ compilers supported a whole zoo of various memory models (tiny, small, large, compact, standard, huge, etc.) each of which could have its own size pointer. If the compilation is done for some more exotic target platform (embedded etc.), then the pointer size may be quite different.
C ++ also has its own special types of "pointers", such as pointers-to-members-class. These types usually have their own special internal structure and their size usually exceeds the size of a regular pointer.
The safest thing is to write a console program with a bunch of sizeof() - remember yourself forever.
- oneSpoiler: pointer is the address. Accordingly, x32 size 4 bytes, x64 - 8 bytes - Alexey Sarovsky
- 2Only if it is not a pointer to a member. - Mikalai Ramanovich