0
0
C++programming~5 mins

Pointer arithmetic in C++

Choose your learning style9 modes available
Introduction

Pointer arithmetic helps you move through memory locations easily. It lets you access elements in arrays or blocks of memory by adding or subtracting numbers to pointers.

When you want to loop through an array using pointers instead of indexes.
When working with dynamic memory and you need to move between allocated blocks.
When you want to access elements in a C-style string by moving the pointer.
When you need to calculate the distance between two memory addresses.
When optimizing code to work directly with memory locations.
Syntax
C++
pointer + n
pointer - n
pointer++
pointer--

Adding or subtracting an integer moves the pointer by that many elements, not bytes.

Increment (++) and decrement (--) move the pointer to the next or previous element.

Examples
Adding 2 moves the pointer to the third element in the array.
C++
int arr[5] = {10, 20, 30, 40, 50};
int *p = arr;

p = p + 2;  // Points to arr[2], value 30
Incrementing pointer moves to the next character in the string.
C++
char str[] = "hello";
char *p = str;

p++;  // Points to 'e' now
Subtracting pointers gives the number of elements between them.
C++
int *p1 = &arr[4];
int *p2 = &arr[1];

int diff = p1 - p2;  // diff is 3
Sample Program

This program shows how to move a pointer through an array and access elements by changing the pointer position.

C++
#include <iostream>

int main() {
    int numbers[] = {5, 10, 15, 20, 25};
    int *ptr = numbers;  // points to numbers[0]

    std::cout << "First element: " << *ptr << "\n";

    ptr = ptr + 3;  // move pointer to numbers[3]
    std::cout << "Fourth element: " << *ptr << "\n";

    ptr--;
    std::cout << "Third element after decrement: " << *ptr << "\n";

    int diff = ptr - numbers;  // distance from start
    std::cout << "Pointer is " << diff << " elements from start" << "\n";

    return 0;
}
OutputSuccess
Important Notes

Pointer arithmetic depends on the type size. For example, adding 1 to an int* moves by sizeof(int) bytes.

Be careful not to move pointers outside the array bounds; it causes undefined behavior.

Pointer subtraction only works if both pointers point to elements of the same array.

Summary

Pointer arithmetic lets you move through arrays by adding or subtracting numbers to pointers.

Increment and decrement operators move pointers to next or previous elements.

Subtracting pointers gives the number of elements between them.