C++ Pointer Arithmetic
Pointers are one of the most powerful features in C++ that allow direct manipulation of memory. Pointer arithmetic refers to performing arithmetic operations on pointers to navigate through memory locations, usually to access elements of arrays or dynamic memory blocks. This topic is crucial for understanding low-level memory management, array operations, and advanced C++ programming techniques.
Pointer arithmetic works because a pointer stores the address of a variable, and when performing arithmetic operations, the compiler automatically scales the arithmetic by the size of the data type the pointer points to. For example, incrementing an int pointer increases its value by sizeof(int) bytes.
1. Basic Concepts
In C++, a pointer is a variable that stores the memory address of another variable. The fundamental idea behind pointer arithmetic is that we can perform operations like addition, subtraction, increment, or decrement directly on the pointer itself, which allows us to traverse arrays or memory blocks efficiently.
For example, consider an integer variable `int num = 10;` and a pointer `int *ptr = #`. The pointer `ptr` contains the memory address of `num`. When we increment `ptr`, it moves to the next memory location suitable for an integer (usually 4 bytes on most systems).
2. Pointer Increment and Decrement
Incrementing a pointer moves it to point to the next memory location of the same data type. Decrementing moves it to the previous memory location. These operations are extremely useful when traversing arrays using pointers.
#include <iostream>
using namespace std;
int main() {
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr; // Points to first element
cout << "Pointer initially points to: " << *ptr << endl;
ptr++;
cout << "After increment, pointer points to: " << *ptr << endl;
ptr--;
cout << "After decrement, pointer points to: " << *ptr << endl;
return 0;
}
Output: Pointer initially points to: 10 After increment, pointer points to: 20 After decrement, pointer points to: 10
3. Pointer Addition and Subtraction
You can add or subtract an integer value to a pointer. This moves the pointer forward or backward in memory by that many elements of the pointer's type.
#include <iostream>
using namespace std;
int main() {
int arr[5] = {5, 10, 15, 20, 25};
int *ptr = arr;
cout << "ptr points to: " << *ptr << endl;
ptr = ptr + 3;
cout << "After adding 3, ptr points to: " << *ptr << endl;
ptr = ptr - 2;
cout << "After subtracting 2, ptr points to: " << *ptr << endl;
return 0;
}
Output: ptr points to: 5 After adding 3, ptr points to: 20 After subtracting 2, ptr points to: 10
4. Subtraction Between Pointers
You can also subtract one pointer from another if both pointers point to elements of the same array. The result is the number of elements between the two pointers, not the difference in memory addresses in bytes.
#include <iostream>
using namespace std;
int main() {
int arr[5] = {10, 20, 30, 40, 50};
int *ptr1 = &arr[1]; // Points to 20
int *ptr2 = &arr[4]; // Points to 50
cout << "Number of elements between ptr1 and ptr2: " << ptr2 - ptr1 << endl;
return 0;
}
Output: Number of elements between ptr1 and ptr2: 3
5. Pointer Comparison
Pointers can be compared using relational operators such as ==, !=, <, <=, >, >=. This is useful when iterating through arrays or memory blocks.
#include <iostream>
using namespace std;
int main() {
int arr[3] = {1, 2, 3};
int *ptr1 = &arr[0];
int *ptr2 = &arr[2];
if (ptr1 < ptr2) {
cout << "ptr1 points to a lower memory address than ptr2" << endl;
}
return 0;
}
Output: ptr1 points to a lower memory address than ptr2
6. Pointer Arithmetic with Arrays
Pointer arithmetic is most commonly used with arrays. Since arrays store elements in contiguous memory, pointers can be incremented or decremented to traverse the array elements efficiently.
#include <iostream>
using namespace std;
int main() {
int arr[5] = {100, 200, 300, 400, 500};
int *ptr = arr;
for (int i = 0; i < 5; i++) {
cout << *(ptr + i) << " "; // Access elements using pointer arithmetic
}
return 0;
}
Output: 100 200 300 400 500
7. Pointer Arithmetic with Dynamic Memory
Pointer arithmetic is especially useful with dynamically allocated memory. When you allocate an array dynamically using `new`, pointers allow easy traversal without using array indices.
#include <iostream>
using namespace std;
int main() {
int *ptr = new int[4]{10, 20, 30, 40};
for (int i = 0; i < 4; i++) {
cout << *(ptr + i) << " ";
}
delete[] ptr; // Free memory
return 0;
}
Output: 10 20 30 40
8. Important Caveats
1. Pointer arithmetic is only safe within the bounds of an array or allocated memory. 2. Accessing memory outside bounds leads to undefined behavior. 3. Incrementing or decrementing pointers not pointing to valid memory is dangerous. 4. The compiler scales arithmetic based on the size of the data type.
9. Advanced Examples
Pointers can be combined with multi-dimensional arrays. For example, in a 2D array, a pointer to the first row can be incremented to access subsequent rows.
#include <iostream>
using namespace std;
int main() {
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
int (*ptr)[3] = matrix; // Pointer to an array of 3 ints
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
cout << *(*(ptr + i) + j) << " ";
}
cout << endl;
}
return 0;
}
Output: 1 2 3 4 5 6
Conclusion
Pointer arithmetic is a fundamental concept in C++ that allows efficient memory manipulation. By understanding pointer increment, decrement, addition, subtraction, and comparison, developers can traverse arrays and dynamic memory efficiently. While powerful, pointer arithmetic requires careful attention to avoid accessing memory out of bounds, which can lead to undefined behavior. Mastery of this concept is essential for advanced C++ programming, including dynamic data structures, system-level programming, and memory optimization.
Always remember that pointer arithmetic is scaled according to the size of the data type the pointer refers to, and only perform arithmetic on pointers pointing to valid memory. When combined with arrays, dynamic memory, and multi-dimensional arrays, pointer arithmetic becomes an indispensable tool for any serious C++ programmer.
Codecrown