What is a Pointer?
In C, a Pointer is a variable whose value is a memory address.
Think of RAM as a massive array of bytes. Each byte has a unique numerical index called its address. When you declare int x = 5;, the compiler allocates space in that array to hold the value 5. A pointer to x simply holds that numerical index.
Operators of Power: & and *
- The Address-of Operator (
&): Returns the memory address of an object. - The Indirection (Dereference) Operator (
*): Accesses the value at the address held by a pointer.
int x = 42;
int *p = &x; // 'p' holds the address of 'x'
printf("%d", *p); // Goes to the address in 'p' and reads the value (42)
*p = 100; // Goes to the address in 'p' and overwrites it with 100
Pointers and Types
Why do we need different types of pointers (like int*, char*, double*) if every pointer just holds an address?
The type of a pointer tells the compiler:
- How many bytes to read/write when dereferencing.
- How to interpret those bytes (e.g., as a signed integer or a floating-point number).
- Instruction Scaling: How many bytes to jump when performing pointer arithmetic (e.g.,
p + 1jumps by 4 bytes for anint*but only 1 byte for achar*).
The NULL Pointer
A NULL pointer is a pointer that points to “nothing” (usually address 0).
- It is used to signify that a pointer is not yet initialized or that a search/allocation failed.
- DANGER: Dereferencing a
NULLpointer is Undefined Behavior and usually triggers a Segmentation Fault.
Dereferencing
int y = 10; int *ptr = &y; // How do we change the value of y to 20 using only ptr? = 20;
Why Use Pointers?
If pointers are so dangerous, why does C use them so heavily?
- Efficiency: Instead of copying a 10,000-byte structure into a function, we pass an 8-byte pointer (on 64-bit systems).
- Dynamic Memory: Pointers are the only way to access memory allocated at runtime (the Heap).
- Hardware Access: Pointers allow us to map specific memory addresses to hardware registers (common in embedded systems).
Interactive Lab
Waiting for signal...
Pointer Decay (Recap)
Remember that in C, the name of an array decodes to the address of its first element. Thus, int *p = arr; is shorthand for int *p = &arr[0];.