Pointers & Arrays
Overview
One of the most mind-bending secrets in C++ is that Arrays and Pointers are structurally the same thing. When you create an array (int arr[5]), the variable name arr is fundamentally just a constant pointer holding the exact memory address of the very first element (index 0).
This is why passing an array into a function is so fast. The compiler doesn't copy all 10,000 items; it simply passes the memory address (the pointer) of the first item, allowing the function to access the original array in memory.
Syntax
int arr[3] = {10, 20, 30};
// 1. The Array Name is a Pointer!
// This prints the exact same memory address!
std::cout << arr << "\n";
std::cout << &arr[0] << "\n";
// 2. Dereferencing the Array Name
// Since 'arr' points to index 0, dereferencing it gets the first value (10)
std::cout << *arr << "\n";
// 3. Pointer Array Traversal
int* ptr = arr; // ptr now points to index 0
std::cout << ptr[1] << "\n"; // Prints 20! Pointers can use array brackets!Common Pitfalls
- Array Decay. When you pass an array to a function
void process(int arr[]), it 'decays' into a standard pointerint* arr. Because it is now just a pointer, callingsizeof(arr)inside the function will return 8 (the size of a pointer), NOT the size of the array! You lose the length entirely. - Trying to reassign an array name.
arris a constant pointer. You cannot writearr = &anotherVariable;. It is permanently locked to its memory block.
Interview Questions
[ ]) on a standard pointer?Because the bracket syntax arr[index] is literally just syntactic sugar (a compiler trick). Behind the scenes, the compiler instantly rewrites arr[index] into pointer arithmetic: *(arr + index). Since pointers and arrays are mathematically identical under the hood, the brackets work on both.
Real-World Example
Demonstrating how array bracket syntax is physically converted into Pointer Arithmetic.
#include <iostream>
int main() {
int data[3] = {5, 10, 15};
// These two lines are mathematically identical to the compiler!
std::cout << data[1] << "\n"; // Bracket syntax (10)
std::cout << *(data + 1) << "\n"; // Pointer arithmetic (10)
return 0;
}Check Your Knowledge
Test your understanding of Pointers & Arrays with these quick questions.