What REALLY happens in memory
When you write:
The computer does three things:
Reserves 4 bytes in RAM (for int)
Stores value
10in those bytesAssigns a unique address to that memory
Example (imaginary):
Now x means:
“Go to address 0x1000 and read value”
Adding a Pointer
Now:
Key understanding:
xstores datapstores address*pmeans:
go to address stored inp, then read value
Why *p Works (CPU level)
When CPU sees:
Steps:
Read address stored in
p(0x1000)Go to that memory
Overwrite value with
50
So memory becomes:
That is why:
No magic. Only memory access.
Pointer Rebinding (Very Important)
A pointer can change where it points, but a variable cannot.
What changed?
Address inside
pNot
a, notb
Memory:
This makes pointers dynamic memory tools.
Pointers with Arrays (EXTREMELY IMPORTANT)
What an Array REALLY Is
Memory layout:
Array elements are:
• Contiguous
• Same data type
• Fixed spacing
Why arr Behaves Like a Pointer
The name arr means:
address of the first element
So:
Both give:
But IMPORTANT:
arris NOT a pointer variableIt is a constant memory address
You cannot do:
Pointer Assigned to Array
Now:
So:
*p→ 10*(p+1)→ 20*(p+2)→ 30
Why (p + 1) Works
Pointer arithmetic depends on data type size.
If:
Then:
Because:
int= 4 bytes
CPU automatically multiplies:
You do NOT add bytes manually.
Equivalence Rule (CORE RULE)
These are IDENTICAL:
All four mean:
value at memory location of ith element
Pointer Arithmetic
Allowed Operations
✔ p + n
✔ p - n
✔ p++, p--
✔ p2 - p1
❌ p + p
❌ p * p
Pointer Increment Internals
Means:
Not:
Example: Walking Through Array Memory
Memory walk:
CPU calculation:
This is how arrays work internally.
Pointer Difference (Memory Distance)
Why?
Difference measured in elements
Not bytes
Used in:
Array length calculation
Iterators
Algorithms
Example 1: Reverse Array Using Pointer Arithmetic
This works because:
Pointers move through memory
No indexing needed
Example 2: Sum Using Pointer Walk
Pointer walks memory sequentially.
Example 3: Modify Values via Pointer
Now array becomes:
Memory directly changed.
VERY IMPORTANT MEMORY RULES
• Pointer must always point to valid memory
• Never access beyond array bounds
• Pointer arithmetic outside array = undefined behavior
• Pointer does NOT know array size
• Programmer must control limits