Addition of Constant to Pointers
We can add integer values to Pointers and the pointer is adjusted based on the size of the data type it points to. For example, if an integer pointer stores the address 1000 and we add the value 5 to the pointer, it will store the new address as:
1000 + (5 * 4(size of an integer)) = 1020
Example
The below C++ code demonstrates the addition of a constant to a pointer.
// CPP program to demonstrate the addition of a constant to
// a pointer
#include <iostream>
using namespace std;
int main()
{
int num = 20;
int* ptr = #
cout << "Address stored in ptr: " << ptr << endl;
// Adding the integer value 1 to the pointer ptr
ptr = ptr + 1;
cout << "Adding 1 to ptr: " << ptr << endl;
// Adding the integer value 2 to the pointer ptr
ptr = ptr + 2;
cout << "Adding 2 to ptr: " << ptr << endl;
return 0;
}
Output
Address stored in ptr: 0x7ffdb8634a94 Adding 1 to ptr: 0x7ffdb8634a98 Adding 2 to ptr: 0x7ffdb8634aa0
Explanation
We have initialized a variable of integer type and then initialized a pointer ‘ptr’ of integer type with an address of a variable ‘num’. Now, we print the address stored in pointer ‘ptr’ after that we have added ‘1’ to ptr and then again print the address stored in ptr. Now we can see in the output that the ‘4’ is added to ptr instead of ‘1’. This is because when we add any constant to the pointer, it first multiplies it to the size of the type of pointer which is ‘integer’ in this case and here it takes 4 bytes. so, it first multiplies ‘1’ with ‘4’ and then adds the (1*4) to the pointer. The same will happen when we add 2, (2*4) will be added to the pointer ‘ptr’.
C++ Pointer Arithmetic
In C++, pointer variables are used to store the addresses of other variables, functions, structures, and even other pointers and we can use these pointers to access and manipulate the data stored at that address.
Pointer arithmetic means performing arithmetic operations on pointers. It refers to the operations that are valid to perform on pointers. Following are the arithmetic operations valid on pointers in C++:
- Incrementing and Decrementing Pointers
- Addition of Constant to Pointers
- Subtraction of Constant from Pointers
- Subtraction of Two Pointers of the Same Type
- Comparison of Pointers
We will explore all the operations listed above in detail with examples.
Prerequisite: To understand pointer arithmetic in C++, we should know Pointers in C++.