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.
Pointer arithmetic in 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.
int arr[5] = {10, 20, 30, 40, 50}; int *p = arr; p = p + 2; // Points to arr[2], value 30
char str[] = "hello"; char *p = str; p++; // Points to 'e' now
int *p1 = &arr[4]; int *p2 = &arr[1]; int diff = p1 - p2; // diff is 3
This program shows how to move a pointer through an array and access elements by changing the pointer position.
#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; }
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.
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.