Pointer arithmetic in C++ involves performing arithmetic operations on pointers. Pointers are variables that store memory addresses, and pointer arithmetic involves performing arithmetic operations on the values stored in these memory addresses.
Pointer arithmetic can be used to traverse arrays, manipulate variable arguments and pointers, and allocate and deallocate memory.
The basic arithmetic operations that can be performed on pointers include addition, subtraction, increment, and decrement. These operations are shown below:
-
Addition: When we add two pointers, the result is a new pointer that points to the memory address that is the sum of the two original addresses. The resulting pointer can be used to access the memory location in question.
-
Subtraction: When we subtract two pointers, the result is an integer value that represents the number of elements between the two memory addresses. This operation is only valid if both pointers point to elements in the same array.
-
Increment: When we increment a pointer by 1, it points to the next element in an array. Similarly, when we decrement a pointer by 1, it points to the previous element in an array.
For example, consider the following code:
int arr[] = {1, 2, 3, 4, 5};
int *ptr = arr;
cout << *ptr << endl; // Output: 1
ptr++; // Increment pointer
cout << *ptr << endl; // Output: 2
ptr--; // Decrement pointer
cout << *ptr << endl; // Output: 1
- Comparison: Pointers can also be compared using relational operators. For example, we can check if two pointers point to the same memory location or if one pointer is greater than another.
For example, consider the following code:
int arr[] = {1, 2, 3, 4, 5};
int *ptr1 = arr;
int *ptr2 = &arr[3];
if (ptr1 == ptr2)
cout << "Pointers are equal." << endl;
else if (ptr1 < ptr2)
cout << "ptr1 is less than ptr2." << endl;
else
cout << "ptr1 is greater than ptr2." << endl;
In summary, pointer arithmetic is a powerful feature of C++ that allows us to manipulate memory addresses directly. However, it is important to be careful when using pointer arithmetic, as it is easy to accidentally access invalid memory locations or overwrite data.