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

  1. Pointer arithmetic means performing operations on pointers to navigate memory addresses.
  2. Common operations:
  3. Increment (ptr++) – moves pointer to the next memory location
  4. Decrement (ptr--) – moves pointer to the previous memory location
  5. Addition (ptr + n) – moves pointer by n elements
  6. Subtraction (ptr - n) – moves pointer backward by n elements

Note: Pointer arithmetic is based on data type size. For example, an int* increment moves by sizeof(int) bytes.

2. Syntax Examples


int *ptr;
ptr++; // move to next int location
ptr--; // move to previous int location
ptr = ptr + 2; // move forward by 2 int locations
ptr = ptr - 3; // move backward by 3 int locations

3. Example Program: Pointer Arithmetic with Arrays


#include <stdio.h>

int main() {
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr; // pointer points to first element

printf("Array elements using pointer arithmetic:\n");
for(int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i, *ptr);
ptr++; // move to next element
}

return 0;
}

Sample Output:


Array elements using pointer arithmetic:
Element 0: 10
Element 1: 20
Element 2: 30
Element 3: 40
Element 4: 50

4. Example Program: Pointer Subtraction


#include <stdio.h>

int main() {
int arr[5] = {5, 10, 15, 20, 25};
int *ptr1 = &arr[4]; // points to last element
int *ptr2 = &arr[1]; // points to second element

printf("Distance between ptr1 and ptr2: %ld\n", ptr1 - ptr2);

return 0;
}

Sample Output:


Distance between ptr1 and ptr2: 3

Explanation: Pointer subtraction gives the number of elements between two pointers of the same array.

5. Key Points to Remember

  1. Pointer arithmetic is scaled by the size of the data type
  2. Increment (ptr++) moves to the next element, not the next byte
  3. Subtraction gives the distance between two pointers in elements
  4. Useful for array traversal, dynamic memory, and low-level memory operations