C++ Pointer Arithmetic

Pointer arithmetic in C++ allows you to perform operations on pointers such as incrementing, decrementing, and finding the difference between pointers. This is commonly used with arrays, where pointers can traverse array elements efficiently.

Pointer Arithmetic Operators

  • + – Increments the pointer by a given number of elements.
  • – Decrements the pointer by a given number of elements or finds the difference between two pointers.
  • ++ – Increments the pointer to point to the next element.
  • – Decrements the pointer to point to the previous element.

Example: Pointer Arithmetic with Array

#include <iostream>
using namespace std;

int main() {

    int arr[5] = {10, 20, 30, 40, 50};
    int *ptr = arr; // Pointer to the first element

    cout << "Accessing array elements using pointer arithmetic:" << endl;

    for(int i = 0; i < 5; i++) {
        cout << "Element " << i << ": " << *(ptr + i) << endl;
    }

    // Increment pointer
    ptr++;
    cout << "After ptr++, points to: " << *ptr << endl;

    // Decrement pointer
    ptr--;
    cout << "After ptr--, points back to: " << *ptr << endl;

    return 0;
}

Output

Accessing array elements using pointer arithmetic:
Element 0: 10
Element 1: 20
Element 2: 30
Element 3: 40
Element 4: 50
After ptr++, points to: 20
After ptr--, points back to: 10

Example: Difference Between Pointers

#include <iostream>
using namespace std;

int main() {

    int arr[5] = {10, 20, 30, 40, 50};
    int *ptr1 = &arr[0];
    int *ptr2 = &arr[3];

    cout << "Difference between ptr2 and ptr1: " << (ptr2 - ptr1) << endl;

    return 0;
}

Output

Difference between ptr2 and ptr1: 3

Important Notes

  • Pointer arithmetic is only meaningful for pointers pointing to elements of the same array or memory block.
  • Incrementing or decrementing a pointer moves it by the size of the data type it points to.
  • Be cautious not to access memory outside the array bounds to avoid undefined behavior.

Next Topic

Next, learn about Pointers and Arrays in C++.