Pointers in C: Definition, Types, Examples, and Applications
In C programming, a pointer is a variable that stores the memory address of another variable. Instead of holding actual data, pointers hold the location of data in memory. This makes pointers a powerful feature of C that enables direct memory access and efficient programming.
int x = 10;
int *p = &x; // pointer 'p' stores the address of variable x
Why Use Pointers?
- To access and manipulate memory directly.
- To work with arrays and strings efficiently.
- To pass large structures or arrays to functions without copying data.
- For dynamic memory allocation (malloc, calloc, free).
- For implementing data structures like linked lists, trees, etc.
Pointer Declaration and Initialization
data_type *pointer_name;
int a = 5;
int *p = &a; // p stores the address of a
Here:
&
β Address-of operator (gives address of a variable).*
β Dereference operator (gives value stored at an address).
Example Program
#include <stdio.h>
int main() {
int x = 10;
int *p; // pointer declaration
p = &x; // storing address of x in pointer p
printf("Value of x: %d\\n", x);
printf("Address of x: %p\\n", &x);
printf("Value stored in pointer p: %p\\n", p);
printf("Value pointed by p: %d\\n", *p);
return 0;
}
Types of Pointers in C
1. Null Pointer
int *p = NULL;
A pointer that doesnβt point to any valid memory address.
2. Void Pointer
void *ptr;
A generic pointer that can point to any data type.
3. Wild Pointer
An uninitialized pointer that points to a random memory location (dangerous).
4. Dangling Pointer
A pointer that points to a memory location which has been freed or deleted.
5. Function Pointer
void (*funPtr)(int, int);
Used to store the address of a function.
6. Pointer to Pointer
int x = 10;
int *p = &x;
int **pp = &p;
A pointer that stores the address of another pointer.
Pointer Arithmetic
Pointers support arithmetic operations like ++
, --
, +
, -
.
Operation | Description |
---|---|
p++ | Moves pointer to next memory location |
p– | Moves pointer to previous memory location |
p + n | Moves pointer forward by n locations |
p – n | Moves pointer backward by n locations |
Applications of Pointers
- Dynamic memory management (
malloc()
,calloc()
,free()
). - Efficient array and string handling.
- Passing variables by reference to functions.
- Creating advanced data structures like linked lists, trees, graphs.
- Implementing system-level programming (OS, device drivers).