If I define a variable in C (i.e. unsigned short int n = 5), that value is stored somewhere in the user's RAM in binary (in this case it would look something like 0000 0000 0000 0101). The place in which that value is stored has an address that is also in binary. (i.e. the value 5 could be stored at say 0010 which would mean it uses both 0010 and 0011 in ram since it uses 2 bytes). The name of the variable n represents the memory address where that value is stored. Where is that memory address stored? Wouldn't that take up even more ram? If it did then wouldn't that address have to have an address as well?
The memory address of a variable is not stored directly in memory. It is part of the code that accesses the variable. Depending on the exact circumstances, it's either an offset (distance from a known place - for example the stack pointer for a local variable, and for a global variable it may be the program counter) or an absolute address (only for global variables).
If you want a variable to store the address of a variable, then yes, you need memory for that variable too. This type of variable is called a pointer.
It depends on several factors, such as the allocation method (stack or static), how the variable is accessed, but let's assume this piece of code:
static int n = 5;
printf("%p\n", &n);
In this case, the address of n
is stored in the code segment, where printf
is called. If you disassemble the code, you'll find a push
instruction, pushing an address to the stack, right before calling printf
. The address being pushed is the address of n
(it's one of two addresses being pushed, there's also the format string).
As I said above, it isn't always the same way. Different architectures and compilation flags (e.g. -fpic
) can change it.
Also, if the variable is on the stack, or if the reference to it is not from code, but from data (e.g. int n=5; int *p = &n;
), things change.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With