In C++, all pointer addresses are fixed in size, that is, they are all 4 bytes in size. The essence of an address is a string of machine codes of 0 and 1. Any variable occupies an address, and the 0- 1 code in this address space is the value of this variable. Different data types occupy different sizes of space, but they all have an address, which is the basis of hardware access, and the name is just a convenient way for programmers to remember this address. However, different variables are all 0- 1 codes in the machine, so it is impossible to judge its type simply by checking the bits of a value.
For example, it is defined as follows:
【cpp】? View the plain? copy
int? a; & lt span? style="font-size:? 14px; ”& gt
Floating? b;
Double? c;
Dragon? Double? d & lt/span>。
(Assuming that they occupy bytes of 4, 8, 8 and 10 respectively, and they are continuously stored in an address space with the starting address of 100, we can get the following memory allocation. ) The variable A is 0- 1 code in a 4-byte storage space, starting from the address 100 and ending at the address 103. The variable b consists of 0- 1 codes in an 8-byte storage space, starting from the address 104 and ending at the address 1 12. In the machine, these memories are all continuous 0- 1 codes. The machine doesn't know that 100~ 103 is an integer, and104 ~1/is a floating point number. All these types are told by the compiler. When we use a, because a is defined as int, the compiler knows to take four bytes backwards from the address of a and then interpret it as int. Then (float)a takes out the value according to the int type first, and then converts the value into the float type according to the rules from int to float. Note: the pointer address only points to the memory location where the data is stored, and the type of the specific variable is told by the compiler.
Second, pointer conversion
Pointer occupies a 4-byte address space (because the addressing space of a program is 2 to the 32nd power, that is, 4GB, so the pointer can point to the space that any program can address with 4 bytes, so the size of the pointer is 4 bytes), and its value is the address of another thing, which can be an ordinary variable, structure, function and so on. Because the size of the pointer is 4 bytes, we can cast the pointer to int or other types. Similarly, we can also convert any constant into int type and assign it to a pointer. The space occupied by all pointers is 4 bytes. They just declare different types, and their values are all addresses pointing to something. For machines, they are not essentially different, and they can perform forced type conversion.