C++ Pointer Arithmetic
In this page:
Incrementing a Pointer
Incrementing a pointer with ptr++ doesn't simply add 1 to the raw address value — it advances the pointer by exactly the size, in bytes, of the type it points to, so an int* moves forward 4 bytes while a double* moves forward 8. This is precisely what makes ptr++ correctly land on the next element of an array rather than the middle of the current one.
Example: Incrementing a Pointer
#include <iostream>
int main() {
int arr[] = {10, 20, 30};
int *ptr = arr;
ptr++;
std::cout << *ptr << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Decrementing a Pointer
Decrementing with ptr-- works the same way in reverse, stepping the pointer backward by one full element's worth of bytes rather than by a single raw byte, which is essential for walking backward through an array correctly.
Example: Decrementing a Pointer
#include <iostream>
int main() {
int arr[] = {10, 20, 30};
int *ptr = &arr[2];
ptr--;
std::cout << *ptr << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Adding and Subtracting Integers
Adding or subtracting an integer n directly, like ptr + n, moves the pointer forward or backward by n full elements at once rather than n raw bytes — this is how you can jump straight to the fifth element of an array with ptr + 4 instead of incrementing one step at a time in a loop.
Example: Adding and Subtracting Integers
#include <iostream>
int main() {
int arr[] = {10, 20, 30, 40};
int *ptr = arr;
std::cout << *(ptr + 2) << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Subtracting Two Pointers
Subtracting one pointer from another of the same type, like ptr2 - ptr1, gives you the number of elements separating them, not the raw byte distance — this is exactly how the standard library computes distances between iterators pointing into the same array or container.
Example: Subtracting Two Pointers
#include <iostream>
int main() {
int arr[] = {10, 20, 30, 40};
int *ptr1 = &arr[0];
int *ptr2 = &arr[3];
std::cout << ptr2 - ptr1 << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Comparing Pointers
Pointers into the same array can be compared with <, >, and == to check their relative positions, which is a common technique for detecting when a pointer has reached the end of an array (ptr == arr + size) or for controlling loops that walk a range using pointers instead of indices.
Example: Comparing Pointers
#include <iostream>
int main() {
int arr[] = {10, 20, 30};
int *ptr1 = &arr[0];
int *ptr2 = &arr[2];
if (ptr1 < ptr2) {
std::cout << "ptr1 comes before ptr2" << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: