What is a Pointer in C?
A pointer is a variable that stores the memory address of another variable. Instead of holding data like 42, it holds the RAM location where that data is stored.
Memory analogy: RAM is like a hotel with numbered rooms. A pointer stores the room number, not the guest (value) inside.
Two Key Pointer Operators
| Operator | Name | Meaning | Example |
|---|---|---|---|
| & | Address-of | Gets memory address of a variable | &num → address of num |
| * | Dereference | Gets value at an address | *ptr → value at address ptr |
c
#include <stdio.h>
int main() {
int num = 42;
int *ptr; // pointer variable — stores an address
ptr = # // ptr now holds address of num
printf("Value of num : %d\n", num); // 42
printf("Address of num : %p\n", &num); // e.g. 0x7ffd1234abc0
printf("Value of ptr : %p\n", ptr); // same as &num
printf("Value at ptr(*ptr): %d\n", *ptr); // 42 (same as num)
// MODIFYING original through pointer
*ptr = 100; // changes num to 100!
printf("\nAfter *ptr = 100:\n");
printf("num = %d\n", num); // 100!
printf("*ptr = %d\n", *ptr); // 100
return 0;
}▶ Output
Value of num : 42 Address of num : 0x7ffd1234abc0 Value of ptr : 0x7ffd1234abc0 Value at ptr(*ptr): 42 After *ptr = 100: num = 100 *ptr = 100
Pointer to Different Types
c
int *ip; // pointer to int
float *fp; // pointer to float
char *cp; // pointer to char
double *dp; // pointer to double
void *vp; // void pointer — points to any typeWhy Are Pointers Important?
- Dynamic memory — malloc(), calloc() for runtime memory allocation
- Arrays — arrays are internally implemented as pointers
- Strings — C strings are char pointers
- Function arguments — pass large data without copying
- Data structures — linked lists, trees, graphs need pointers
- Hardware access — embedded systems, OS development
⚠ Warning: Always initialize a pointer before using it. An uninitialized pointer (wild pointer) points to a random memory location — using it crashes the program!