Topic 40 of 83
Pointers & Arrays
Overview
In C++, an array's name acts as a constant pointer to its first element. Pointers and arrays are deeply intertwined.
Syntax
cpp
int arr[3] = {10, 20, 30};
// arr is implicitly converted to &arr[0]
int* ptr = arr;
cout << ptr[0]; // 10
cout << ptr[1]; // 20Common Pitfalls
- You cannot reassign an array name like a pointer (e.g., `arr = &anotherVar` is illegal because `arr` is a constant pointer).
Interview Tips
- Explain array decay: when passing an array to a function `void func(int arr[])`, it 'decays' into a pointer `void func(int* arr)`. The function loses the size information of the array.
Real-World Example
Iterating an array using a pointer.
example
cpp
#include <iostream>
using namespace std;
int main() {
int arr[] = {1, 2, 3, 4, 5};
int* ptr = arr;
for (int i = 0; i < 5; i++) {
cout << ptr[i] << " ";
}
return 0;
}