Pointer Arithmetic
Overview
Because a Pointer is just a mathematical integer representing a RAM address, you can actually perform math on it! This is called Pointer Arithmetic.
However, it doesn't work like normal math. If an int pointer holds the address 1000, and you do ptr++ (add 1), the address does NOT become 1001. Because an int takes 4 bytes, the compiler perfectly understands that the 'next' integer lives 4 bytes away. It scales the math automatically, jumping the address to 1004.
Syntax
int arr[3] = {10, 20, 30};
int* ptr = arr; // ptr points to 10
// 1. Addition (Moving Forward)
ptr++; // Jumps forward exactly 1 memory block (4 bytes for an int)
std::cout << *ptr << "\n"; // Now prints 20
// 2. Subtraction (Moving Backward)
ptr--; // Jumps backward 1 block
std::cout << *ptr << "\n"; // Back to 10
// 3. Jumps
ptr = ptr + 2; // Jumps forward 2 blocks (8 bytes)
std::cout << *ptr << "\n"; // Prints 30Common Pitfalls
- Walking off a cliff. Pointer arithmetic does absolutely zero bounds checking. If you have a 3-element array and you loop
ptr++10 times, the pointer will march straight out of your array into unauthorized RAM. When you dereference it, the program will segfault and crash violently. - Multiplying or Dividing pointers. You can add or subtract integers from a pointer, and you can subtract two pointers from each other (to find the distance between them). But you CANNOT multiply or divide pointers.
ptr * 2is a compilation error because multiplying a memory address is physically meaningless.
Interview Questions
double* points to memory address 0x1000, what exactly is the memory address after executing ptr = ptr + 3;?The address becomes 0x1018 (which is 1000 + 24 in decimal). Because a double takes 8 bytes of memory, adding 3 to the pointer scales the math: 3 jumps * 8 bytes = 24 bytes forward.
Real-World Example
Using raw pointer arithmetic to loop through an array at blazing speeds without using an index variable.
#include <iostream>
int main() {
int arr[5] = {2, 4, 6, 8, 10};
// We create a pointer to the start, and a pointer to the EXACT end
int* ptr = arr;
int* end = arr + 5;
// Loop until our pointer hits the end address!
while (ptr < end) {
std::cout << *ptr << " ";
ptr++; // Jump to next memory block
}
return 0;
}Check Your Knowledge
Test your understanding of Pointer Arithmetic with these quick questions.