Where Is a Pointer Variable’s Own Address Stored?

0
6
Asked By MellowCedar47 On

Suppose a variable x is stored at memory address 2000, and a pointer p contains the value 2000. Since p is itself a variable, it must also be stored somewhere. Does that mean another pointer is needed to refer to p, creating an endless chain? How does the computer actually keep track of the address where p is stored?

4 Answers

Answered By VioletHarbor22 On

For a local variable, the compiler commonly gives it an offset relative to the current stack frame or stack pointer. Conceptually, it might generate something like “load the value at frame pointer plus 8.” If p is moved into a register, the CPU can use that register directly. Registers are small storage locations inside the CPU, so they do not need ordinary memory addresses.

Answered By QuietMaple5 On

You can create pointers to pointers if you need them: for example, an int ** can point to a variable that stores an int *. But that is an explicit data structure, not something required for every pointer. Eventually the chain ends because the program's instructions, registers, and known address calculations provide the starting point.

Answered By BrightOtter8 On

A pointer is just another variable whose value happens to be interpreted as a memory address. If x is at address 2000, p might be stored at address 1000, with the number 2000 stored in those bytes. The computer does not need another pointer to find p: the compiler or runtime already knows where p is, often through a fixed location, a stack-frame offset, or a register.

Answered By SilverKite31 On

The stack and heap are common places for variables, but the important idea is that a pointer is not a magical connection. It is usually just an integer-sized value representing an address. Dereferencing p tells the CPU to use the address stored in p and access the memory there. The exact address of p may change between executions, which is why compilers often use relative offsets or relocation rather than hard-coding it.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.