Topic 29 of 91 5. C++ Pointers and References Interactive Tutorial

Pointers With Arrays in C++: Traversing Elements Through Addresses

15 mins read Last updated: 26 Sep 2026 21,800 views

Direct Answer & Core Concept

In C++, array names decay into pointers to their first elements (&arr[0]). Pointer arithmetic allows navigating elements where adding an integer n to a pointer (ptr + n) advances the memory address by n * sizeof(T) bytes. Array indexing arr[i] is syntactically equivalent to *(arr + i).

Detailed Explanation & Mechanics

1. Pointer Arithmetic & Scaling:

main.cpp
Run Online
ARRAY MEMORY LAYOUT (int = 4 bytes):
Index:        arr[0]      arr[1]      arr[2]      arr[3]
Address:      0x1000      0x1004      0x1008      0x100C
Pointer:       ptr       ptr + 1     ptr + 2     ptr + 3

2. Equivalences:

arr[i] == *(arr + i) == *(i + arr) == i[arr]

Runnable Code Example: Pointers With Arrays in C++

C++20 / C++23
main.cpp
Run Online
#include <iostream>

int main() {
    int buffer[5] = {10, 20, 30, 40, 50};
    int* ptr = buffer; // Decays to &buffer[0]

    std::cout << "Traversing via Pointer Arithmetic:
";
    for (int i = 0; i < 5; ++i) {
        std::cout << "Element [" << i << "]: " << *(ptr + i) 
                  << " at address: " << (ptr + i) << "
";
    }

    // Pointer difference (number of elements between pointers)
    int* endPtr = buffer + 5;
    std::cout << "Total elements (end - start): " << (endPtr - ptr) << "
";
    return 0;
}

Common C++ Technical Interview Questions & Answers

Interview Prep
Q

Q: What happens when you subtract two pointers in C++?

A: Pointer subtraction (`ptr2 - ptr1`) returns a signed integer of type `std::ptrdiff_t` representing the number of array elements between the two memory addresses, not the raw byte difference.
Q

Q: Why is pointer decay a potential source of bugs?

A: When an array is passed to a function, it decays to a pointer, losing its compile-time size information (i.e. `sizeof(arr)` returns pointer size 8 bytes rather than total array bytes).

Key Takeaways, Modern Best Practices & Idioms

C++ Best Practices & Production Rules

1. Use std::array or std::vector instead of C-style raw arrays to preserve size information.
2. Use std::span (C++20) for non-owning views over contiguous memory buffers.
3. Never increment pointers beyond the past-the-end element (arr + N).
We value your privacy & transparency

OperateTools uses cookies and local storage to ensure basic tool functionality, preserve preferences, and analyze aggregated traffic. We never sell your personal data or index your document files. Learn more in our Privacy Policy.