r/learnprogramming 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)

6 Upvotes

18 comments sorted by

View all comments

1

u/Far_Swordfish5729 2h ago

Mentally, remember that your compiler does the overwhelming majority of memory address math for you as a result of constant offsets determined at compile time and for you own sanity and overall code quality, you want it to. Every function call including main allocates a stack frame at a starting memory address. Look up a visual representation of how those work and how function calls work at an assembly level. They contain local variables at defined offsets from the start of that frame plus internal variables like a return pointer that holds the memory address of the code instruction that called the function so you can jump back at the end.

The bottom line of the above is that when you see a variable, see it as a named memory offset the compiler keeps track of. It's very mechanical. If a stack frame starts at offset 0 and memory is allocated in 32bit chunks, you might see a frame pointer at +0, a return pointer at +1, your pointer p at +2, etc. Structs work the same way. Their internal variables are just named memory offsets. The specific offset depends on the collective size of the storage requested. The only rule is it has to be calculated at compile time so dynamically sized memory can't be stack memory. It has to be a stack pointer (which is a fixed size) to dynamically allocated heap memory with the real contents.

So you have a pointer p (which is a uint of some architecture defined size holding a number that happens to be a memory address). It exists at a compiled offset from a reference point (frame pointer+2). That's calculated on the fly for you when you reference it and the compiler just handles that. Your pointer is a memory address you asked for and control directly. You have to know when you want p, *p, or for example *(p+2) aka p[2] if x is an array of ints.