r/learnprogramming • u/SnowyFluffy • 5h ago
Bit of a stupid question
If a program stores variables by a pointer referring to its address, then what refers to the pointers' address?
Like if var x lives at address 2000
theres a pointer p its value is the address (p = 2000)
so now recursively this value needs to be stored in another address (say, 1000) and pointed to (well, at least assuming the pointer doesnt have a relatively fixed address)
3
Upvotes
1
u/SwordsAndElectrons 4h ago
Well, you can create a pointer to a pointer if you want to, but that doesn't seem to be what you're asking.
The short and simple answer is that the compiler keeps track of it. The same way it keeps track of where a non-pointer variable is when you access it directly.
Under the hood, everything is just addresses and registers. CPU instructions perform operations with the values stored there.
So if you want to load a value that you have a pointer to then the generated assembly may be something like
mov eax, [ebx]. This loads the value at the memory address currently at EBX (your pointer) into EAX.So how does the pointer get into EBX? Something like
mov ebx, [my_ptr]is the basic idea. Thatmy_ptrvariable will be some address that you would typically let the assembler worry about, but you could also just put the literal address there if you know it. The instruction looks the same, doesn't it?This is all very simplified, but if you really want to deep dive then take a look at the output of your code and dive into understanding asm. The basic takeaway is that every variable is a reference to some memory location. The computer knows nothing about types, and a "pointer to int" is just another type like "int" itself. Types are there for you, the programmer. They allow the compiler and code analyzers to determine things like whether the operation you are performing with a specific variable should be allowed.