C++ Pointers and Arrays Relationship: Decay, Offsets & Multi-Dimensional Access

In C and C++, arrays and pointers are intimately linked. An array's name acts as a constant pointer holding the base address of its first element (index 0). Understanding how arrays decay into pointers is essential for mastering C++ systems programming.

Pointer Offset Equivalency

#include <iostream>

int main() {
    int numbers[4] = {100, 200, 300, 400};

    // All three lines produce the EXACT same value:
    std::cout << "numbers[2]:   " << numbers[2] << "\n";     // Subscript syntax -> 300
    std::cout << "*(numbers+2): " << *(numbers + 2) << "\n"; // Pointer arithmetic -> 300
    std::cout << "2[numbers]:   " << 2[numbers] << "\n";     // Valid C++! -> 300

    return 0;
}
BCA Technical Interview Question:

"What is the difference between an Array of Pointers and a Pointer to an Array?"
• int* arr[5];: An array of 5 pointers to integers.
• int (*ptr)[5];: A single pointer that points to an entire array of 5 integers.

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is 'Array Decay' in C++?

Array decay is the implicit conversion of an array name into a pointer to its first element (T*). When an array is passed to a function, it decays into a pointer, losing its compile-time size information.

Q2. Why are arr[i] and *(arr + i) identical in C++?

In C++, the bracket syntax arr[i] is defined as syntactic sugar for *(arr + i). Because addition is commutative, *(i + arr) is also valid, meaning i[arr] compiles to the exact same machine code!

Explore Related C++ Tutorials & Next Steps

Boost your C++ proficiency by studying these closely connected core modules:

C++ Arrays

Array definitions and memory allocation.

C++ Pointers

Pointer arithmetic and dereferencing.

Modern std::array

Avoiding array decay with modern C++ containers.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!