Pointers and Arrays
Relationship between pointers and arrays
Interview Relevant: Common interview topic
Pointers and Arrays
Arrays decay to pointers in most contexts.
Code Examples
Understanding array-pointer relationship.
cpp
1int arr[] = {1, 2, 3, 4, 5};
2
3// Array name is address of first element
4int* ptr = arr; // Same as &arr[0]
5
6// These are equivalent
7arr[2]; // 3
8*(arr + 2) // 3
9ptr[2]; // 3
10*(ptr + 2) // 3
11
12// Key difference: sizeof
13cout << sizeof(arr); // 20 (5 * 4 bytes)
14cout << sizeof(ptr); // 8 (pointer size on 64-bit)
15
16// Array as function parameter decays to pointer
17void process(int* arr, int size); // Must pass size
18void process(int arr[], int size); // Same thing!
19
20// Prevent decay with reference
21template<size_t N>
22void printArray(int (&arr)[N]) {
23 for (int x : arr) cout << x << " ";
24}