Let's take a step back ... it is important to understand that all programming languages (except assembly language) describe the abstraction of a problem in terms that are supposed to be simple for programmers. The task of the compiler is to read this abstract description and generate a lower-level description that corresponds directly to the device.
When you write:
int x = 6;
you tell the compiler that you want to use the integer variable that you want to call this variable x, and that you want the variable to have a value of 6.
One of the tasks of the compiler is to decide how to save this variable. C ++ describes various kinds of variables that help the compiler decide which type of storage is appropriate.
A local variable (declared inside a function) is usually stored in memory on the stack, but a small amount (for example, an integer) can be stored in the register.
A global or static variable will be stored in memory.
The compiler remembers where he decided to save this value so that he can find it again - for a local varaible, which will be the name of the register or the address relative to the top of the stack; for global or static, this is the address relative to the start of all program data.
The actual address in memory is unknown until the program has been compiled, connected, and loaded into memory (since the OS may not always load the program at the same address) - it is important that the compiler knows where the variable will be and that it can generate code for access to it.
If, as in your second question, the type of the variable is some data structure that the compiler chooses where to place it in memory in the same way. When your program accesses a member of this structure, the compiler can work out the address of the member because it knows the address of the structure, as well as the offset of the member within the structure.
So, in the case of your example person p , when the program refers to p1.type2 , the compiler takes the address p and adds the offset type2 (which will probably be 4, because the first part of your struct person occupied with type1 , which is an integer that is is 4 bytes (on most 32-bit architectures)).
You must specify both p and type2 , because you may have another person (say q ), and the compiler needs to be told who you are trying to manipulate with. p.type2 not the same variable as q.type2 , and will have a different address.
dajames
source share