0
0
C++programming~15 mins

Pointer arithmetic in C++ - Deep Dive

Choose your learning style9 modes available
Overview - Pointer arithmetic
What is it?
Pointer arithmetic is the process of performing operations like addition or subtraction on pointers in C++. Pointers hold memory addresses, and arithmetic on them moves the pointer to different memory locations based on the size of the data type they point to. This lets you navigate arrays or blocks of memory efficiently. It is a fundamental concept for working directly with memory in C++.
Why it matters
Without pointer arithmetic, programmers would struggle to access elements in arrays or data structures efficiently, especially when working close to the hardware or optimizing performance. It solves the problem of moving through memory locations in a controlled way. Without it, many low-level tasks like system programming, embedded software, and performance-critical code would be much harder or impossible.
Where it fits
Before learning pointer arithmetic, you should understand basic pointers and how memory addresses work in C++. After mastering pointer arithmetic, you can learn about dynamic memory management, arrays, and advanced data structures that rely on pointers.
Mental Model
Core Idea
Pointer arithmetic moves a pointer through memory by adding or subtracting steps sized to the data type it points to.
Think of it like...
Imagine a pointer as a bookmark in a book where each page is a data element. Adding 1 to the pointer moves the bookmark to the next page, not just the next physical spot, because pages have fixed sizes.
Pointer (address) ──> [Element 0] [Element 1] [Element 2] [Element 3]
                 ↑
               Pointer points here

Adding 1 moves pointer to next element:
Pointer + 1 ──> [Element 1]
Build-Up - 8 Steps
1
FoundationUnderstanding pointers and addresses
🤔
Concept: Pointers store memory addresses of variables.
In C++, a pointer is a variable that holds the address of another variable. For example: int x = 10; int* p = &x; // p holds the address of x Here, p points to x's memory location.
Result
p contains the address of x, not the value 10.
Understanding that pointers hold addresses, not values, is essential before manipulating them with arithmetic.
2
FoundationBasics of pointer arithmetic operations
🤔
Concept: You can add or subtract integers to pointers to move through memory.
Pointer arithmetic means adding or subtracting integers to pointers. For example: int arr[3] = {10, 20, 30}; int* p = arr; // points to arr[0] p = p + 1; // now points to arr[1] This moves the pointer to the next element in the array.
Result
Pointer p now points to the second element of arr, which is 20.
Pointer arithmetic moves pointers by the size of the data type, not by 1 byte.
3
IntermediateHow pointer arithmetic depends on data type size
🤔Before reading on: Do you think adding 1 to a pointer always increases its address by 1 byte? Commit to your answer.
Concept: Pointer arithmetic moves by multiples of the size of the pointed-to type.
If a pointer points to an int (usually 4 bytes), adding 1 increases the address by 4 bytes, not 1. For example: int* p = arr; // address 1000 (example) p = p + 1; // address becomes 1004 This is because each int occupies 4 bytes in memory.
Result
Pointer moves to the next int in memory, skipping 4 bytes.
Knowing that pointer arithmetic scales by data type size prevents errors when navigating arrays.
4
IntermediateSubtracting pointers and pointer difference
🤔Before reading on: If you subtract two pointers pointing inside the same array, do you get a memory address or a count of elements? Commit to your answer.
Concept: Subtracting pointers gives the number of elements between them, not bytes.
Given two pointers p1 and p2 pointing inside the same array, p2 - p1 returns how many elements are between them: int arr[5]; int* p1 = &arr[1]; int* p2 = &arr[4]; int diff = p2 - p1; // diff is 3 This tells you there are 3 elements between p1 and p2.
Result
Pointer subtraction returns element count, not byte difference.
Understanding pointer subtraction as element count helps in array indexing and bounds checking.
5
IntermediateUsing pointer arithmetic with arrays
🤔
Concept: Arrays and pointers are closely related; pointer arithmetic lets you traverse arrays.
An array name acts like a pointer to its first element. You can use pointer arithmetic to access array elements: int arr[3] = {10, 20, 30}; int* p = arr; // Access elements using pointer arithmetic int first = *p; // 10 int second = *(p + 1); // 20 int third = *(p + 2); // 30
Result
You can access array elements by moving the pointer and dereferencing.
Knowing arrays decay to pointers explains why pointer arithmetic works naturally with arrays.
6
AdvancedPointer arithmetic with different data types
🤔Before reading on: Does pointer arithmetic behave the same for all data types regardless of size? Commit to your answer.
Concept: Pointer arithmetic respects the size of the data type, which varies across types.
For example, a char pointer moves by 1 byte per increment, but a double pointer moves by 8 bytes (on most systems): char* cp; double* dp; cp = cp + 1; // moves 1 byte dp = dp + 1; // moves 8 bytes This difference is crucial when working with mixed data types.
Result
Pointer arithmetic adjusts step size based on data type size.
Recognizing data type size differences prevents pointer errors and memory corruption.
7
AdvancedPointer arithmetic and undefined behavior risks
🤔
Concept: Pointer arithmetic outside valid memory bounds causes undefined behavior.
If you move a pointer beyond the allocated memory (like past the end of an array), the program may crash or behave unpredictably: int arr[3]; int* p = arr + 3; // points just past the array (allowed for comparison) int val = *p; // undefined behavior! Accessing invalid memory Always ensure pointers stay within valid ranges.
Result
Accessing memory outside bounds can crash or corrupt programs.
Understanding pointer bounds is critical for safe and correct code.
8
ExpertPointer arithmetic in low-level optimization
🤔Before reading on: Do you think pointer arithmetic can be faster than array indexing in all cases? Commit to your answer.
Concept: Pointer arithmetic can optimize performance by reducing overhead compared to array indexing in some cases.
In performance-critical code, using pointers to traverse arrays can avoid repeated index calculations: int* p = arr; for (int i = 0; i < n; ++i) { process(*p); ++p; } This can be faster than arr[i] because it uses direct pointer increments. However, modern compilers often optimize both similarly.
Result
Pointer arithmetic can improve speed in tight loops, but gains depend on compiler and context.
Knowing when pointer arithmetic offers real performance benefits helps write efficient low-level code.
Under the Hood
At runtime, pointers are just memory addresses stored as integers. Pointer arithmetic adds or subtracts the size of the pointed-to type multiplied by the integer operand to the pointer's address. The CPU uses this adjusted address to access memory. The compiler calculates the size of the data type at compile time to scale pointer arithmetic correctly.
Why designed this way?
Pointer arithmetic was designed to allow efficient navigation of contiguous memory blocks like arrays without manual byte calculations. This abstraction lets programmers think in terms of elements, not raw bytes, reducing errors and improving readability. Alternatives like manual byte offset calculations were error-prone and less intuitive.
Pointer Arithmetic Flow:

[Pointer Address] + (Integer Offset * SizeOf(Type))
          │
          ▼
[New Memory Address]
          │
          ▼
[Access Memory at New Address]
Myth Busters - 4 Common Misconceptions
Quick: Does adding 1 to a pointer always increase its address by 1 byte? Commit to yes or no.
Common Belief:Adding 1 to a pointer always increases its address by 1 byte.
Tap to reveal reality
Reality:Adding 1 to a pointer increases its address by the size of the data type it points to, not 1 byte.
Why it matters:Misunderstanding this causes incorrect memory access and bugs when navigating arrays.
Quick: If you subtract two pointers, do you get a memory address or a count of elements? Commit to your answer.
Common Belief:Subtracting two pointers returns a memory address.
Tap to reveal reality
Reality:Subtracting two pointers returns the number of elements between them, not a memory address.
Why it matters:Confusing this leads to wrong calculations in array indexing and pointer comparisons.
Quick: Can you safely dereference a pointer that points just past the end of an array? Commit yes or no.
Common Belief:You can dereference a pointer that points just past the end of an array safely.
Tap to reveal reality
Reality:Dereferencing a pointer past the end of an array causes undefined behavior and can crash the program.
Why it matters:Ignoring this leads to crashes and security vulnerabilities.
Quick: Does pointer arithmetic behave the same for all data types regardless of size? Commit yes or no.
Common Belief:Pointer arithmetic behaves the same for all data types, moving by 1 byte each time.
Tap to reveal reality
Reality:Pointer arithmetic moves by the size of the data type, which varies (e.g., 1 byte for char, 4 or 8 bytes for int/double).
Why it matters:Assuming uniform step size causes incorrect memory access and data corruption.
Expert Zone
1
Pointer arithmetic can be combined with casting to navigate complex data structures, but this requires careful alignment and type safety considerations.
2
Incrementing pointers in multi-dimensional arrays requires understanding how arrays are laid out in memory (row-major order in C++).
3
Some compilers optimize pointer arithmetic differently depending on optimization flags, so performance can vary unexpectedly.
When NOT to use
Avoid pointer arithmetic when working with non-contiguous data structures like linked lists or when using high-level containers like std::vector, which provide safer iterators. Use iterators or indexing instead for better safety and readability.
Production Patterns
In production, pointer arithmetic is often used in system programming, embedded software, and performance-critical loops. It is combined with careful bounds checking and sometimes with smart pointers or custom memory allocators to manage safety and efficiency.
Connections
Array indexing
Pointer arithmetic underlies array indexing operations.
Understanding pointer arithmetic clarifies how array indexing works at a low level, revealing that arr[i] is equivalent to *(arr + i).
Memory management
Pointer arithmetic is essential for manual memory management and dynamic allocation.
Knowing pointer arithmetic helps understand how to navigate and manipulate dynamically allocated memory blocks safely.
Navigation in linked data structures (e.g., linked lists)
Pointer arithmetic contrasts with pointer usage in linked structures where pointers jump to non-contiguous memory.
Recognizing the difference between pointer arithmetic in arrays and pointer usage in linked structures helps avoid confusion about memory layout and traversal.
Common Pitfalls
#1Moving pointer beyond array bounds and dereferencing.
Wrong approach:int arr[3] = {1,2,3}; int* p = arr + 3; int val = *p; // undefined behavior
Correct approach:int arr[3] = {1,2,3}; int* p = arr + 2; int val = *p; // safe, val = 3
Root cause:Misunderstanding valid pointer ranges and assuming pointers can be dereferenced anywhere.
#2Assuming pointer arithmetic moves by 1 byte always.
Wrong approach:char* cp; cp = cp + 4; // moves 4 bytes int* ip; ip = ip + 4; // mistakenly thought to move 4 bytes, but moves 4 * sizeof(int)
Correct approach:Understand that ip + 4 moves 4 ints, not 4 bytes, so actual byte offset is 4 * sizeof(int).
Root cause:Confusing pointer arithmetic with simple integer addition without considering data type size.
#3Using pointer arithmetic on void pointers.
Wrong approach:void* vp; vp = vp + 1; // error: pointer arithmetic not allowed on void*
Correct approach:Cast void* to a typed pointer before arithmetic: int* ip = (int*)vp; ip = ip + 1;
Root cause:Void pointers have no size, so arithmetic is undefined without casting.
Key Takeaways
Pointer arithmetic moves pointers by the size of the data type they point to, not by single bytes.
Subtracting pointers returns the number of elements between them, not a memory address.
Pointer arithmetic is essential for efficient array traversal and low-level memory manipulation.
Accessing memory outside the valid range of pointers causes undefined behavior and must be avoided.
Understanding pointer arithmetic deepens your grasp of how arrays and memory work in C++.