Pointers Fundamentals: & and * Operators
Pointers are C's most famous and powerful feature. They give you direct access to physical memory addresses in RAM.
What is it?
A pointer is a variable that stores the memory address of another variable.
Why is it used?
Dynamic memory allocation, pass-by-reference in functions, fast array processing, and building data structures (linked lists, trees, graphs).
Detailed Explanation
The Two Fundamental Operators:
1. Address-Of Operator (`&`): Returns the memory address of a variable (e.g. `&age`).
2. Dereference Operator (`*`): Accesses or modifies the value stored at the memory address held by the pointer (e.g. `*ptr = 25`).
Pointer Declaration:
`int *ptr;` declares `ptr` as a pointer to an integer. It holds a hexadecimal memory address (e.g. `0x7ffee4b2c938`). Printed using `%p`.
Syntax Structure
Syntax Blueprint
int x = 10;
int *ptr = &x; // ptr holds address of x
*ptr = 20; // Changes x to 20 through pointer!
Code Example
C Code
#include <stdio.h>
int main() {
int course_fee = 2500;
int *fee_ptr = &course_fee; // Pointer fee_ptr stores address of course_fee
printf("=== Pointer Exploration ===\n");
printf("Value of course_fee: %d\n", course_fee);
printf("Address of course_fee (&): %p\n", (void*)&course_fee);
printf("Value of fee_ptr: %p (Same address!)\n", (void*)fee_ptr);
printf("Value pointed to (*ptr): %d\n", *fee_ptr);
// Modifying the variable through the pointer (Dereferencing)
*fee_ptr = 3000;
printf("\n--- After Mutating via *fee_ptr = 3000 ---\n");
printf("New course_fee value: %d\n", course_fee);
return 0;
}
Explanation of the Code
• `fee_ptr = &course_fee` captures the memory address.
• Printing with `%p` shows the physical memory address in hexadecimal.
• Changing `*fee_ptr` modifies `course_fee` directly in RAM.
Expected Output
=== Pointer Exploration ===
Value of course_fee: 2500
Address of course_fee (&): 0x... (hex memory address)
Value of fee_ptr: 0x... (same address)
Value pointed to (*ptr): 2500
--- After Mutating via *fee_ptr = 3000 ---
New course_fee value: 3000
Real-World Application
Every operating system driver, database memory buffer, and 3D graphics pipeline manipulates data via pointers.
Common Mistakes to Avoid
• Dereferencing an uninitialized pointer (wild pointer), causing immediate crashes (segmentation fault).
• Confusing `*` in declaration (`int *p;`) with `*` in dereference (`*p = 5;`).
Quick Practice Challenge
Declare a `float` variable, assign it 99.5, create a pointer to it, and print its value using dereferencing.
Key Takeaways
• `&` gets the memory address of a variable.
• `*` dereferences the pointer to access or modify the target value.
• Pointers enable high performance and direct memory control.