C++ Pointer Arithmetic

Pointer arithmetic in C++ refers to performing operations (such as addition, subtraction, increment, and decrement) on pointers, which are variables that store memory addresses. This allows you to navigate through the memory locations that the pointers refer to, based on the type of data they point to.

Pointer Arithmetic Operations

1. Incrementing a Pointer (++)

When you increment a pointer, it moves to the next memory location of its type.

The pointer is adjusted based on the size of the data type it points to. For example, if a pointer points to an int, incrementing the pointer will move it by the size of an int (typically 4 bytes on most systems).

Example:


int arr[] = {10, 20, 30, 40, 50};
int* ptr = arr;  // points to arr[0]

ptr++;  // now points to arr[1] (next element)
cout << *ptr << std::endl;  // Output: 20

2. Decrementing a Pointer (--)

When you decrement a pointer, it moves to the previous memory location of its type.

Example:


int arr[] = {10, 20, 30, 40, 50};
int* ptr = arr+1;  // points to arr[1]

ptr--;  // now points to arr[0] (previous element)
cout << *ptr << std::endl;  // Output: 10

3. Pointer Addition (+)

You can add an integer value to a pointer. This moves the pointer forward by that many elements (not bytes), based on the type it points to.

Example:


int arr[] = {10, 20, 30, 40, 50};
int* ptr = arr;  // points to arr[0]

ptr = ptr + 3;  // now points to arr[3]
std::cout << *ptr << std::endl;  // Output: 40

4. Pointer Subtraction (-)

You can subtract an integer value from a pointer, which moves the pointer backward by that many elements.

Example:


int arr[] = {10, 20, 30, 40, 50};
int* ptr = arr + 3;  // points to arr[3]

ptr = ptr - 1;  // now points to arr[2]
std::cout << *ptr << std::endl;  // Output: 30