Pointer Arithmetic in C Programming (Complete Guide with Examples)
This tutorial explains pointer arithmetic in C, which allows you to perform operations on pointers such as increment, decrement, addition, and subtraction. It covers examples to help beginners navigate arrays and memory addresses efficiently using pointers.
1. What is Pointer Arithmetic
- Pointer arithmetic means performing operations on pointers to navigate memory addresses.
- Common operations:
- Increment (
ptr++) – moves pointer to the next memory location - Decrement (
ptr--) – moves pointer to the previous memory location - Addition (
ptr + n) – moves pointer bynelements - Subtraction (
ptr - n) – moves pointer backward bynelements
Note: Pointer arithmetic is based on data type size. For example, an int* increment moves by sizeof(int) bytes.
2. Syntax Examples
3. Example Program: Pointer Arithmetic with Arrays
Sample Output:
4. Example Program: Pointer Subtraction
Sample Output:
Explanation: Pointer subtraction gives the number of elements between two pointers of the same array.
5. Key Points to Remember
- Pointer arithmetic is scaled by the size of the data type
- Increment (
ptr++) moves to the next element, not the next byte - Subtraction gives the distance between two pointers in elements
- Useful for array traversal, dynamic memory, and low-level memory operations