c / c-arrays-strings
20 mins
C Level 5: Memory Addresses & Dereferencing
Why This Matters: Pointers are C's superpower. Mastering addresses (&) and dereferencing (*) is mandatory for system programming.
## Mental Model of C Pointers
A **pointer** is a variable whose stored value is the **memory address** of another variable.
### Essential Pointer Relationship
$$ ext{VARIABLE} longrightarrow ext{VALUE} longrightarrow ext{MEMORY ADDRESS} longrightarrow ext{POINTER} longrightarrow ext{DEREFERENCE}$$
- `&` (Address-of): Obtains the memory location of a variable.
- `*` (Dereference): Accesses or modifies value at stored pointer address.
```c
int val = 42;
int *ptr = &val; // ptr stores address of val
printf("Value: %d
", *ptr); // Dereference => 42
*ptr = 99; // Mutates val directly in RAM!
```
MENTAL MODEL & MEMORY LAYOUT
VARIABLE RELATIONSHIP:
val (0x7fff) ──► [ Value: 42 ]
▲
│ (Dereference *ptr)
ptr (0x7ff0) ──► [ Address: 0x7fff ] COMMON PITFALLS TO AVOID
- Confusing `*` in pointer declaration (`int *p`) with `*` dereference (`*p = 5`).
- Dereferencing uninitialized or NULL pointers (causing Segmentation Faults).
Call-by-Reference Swap Function
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 10, y = 20;
swap(&x, &y);
printf("Swapped: x=%d, y=%d\n", x, y);
return 0;
}Swaps values in caller scope by passing memory addresses instead of scalar copies.
CONCEPT MASTERY CHECKPOINT
If `int x = 5; int *p = &x;`, what does `*p = 20;` do?
NEXT RECOMMENDED LESSON
C Level 6: Dynamic Memory Management
Challenge: Write a function `void increment(int *p)` that increases the value stored at pointer p by 1.