π₯ C++ Arrays: Complete Guide with Examples | Playlist
Playlist Link: C++ Series by TheCherno
π Introduction to Arrays
Video Reference: Start at 0:00
Arrays store collections of elements contiguously in memory. Key features:
- Fixed size (declared at compile-time for stack arrays).
- Zero-based indexing.
- Contiguous memory layout (elements stored sequentially).
π§© Stack-Allocated Arrays
Video Reference: 1:38
int example[5]; // β Uninitialized
int numbers[5] = {2, 2, 2, 2, 2}; // β
Initialized
// Access/Modify
numbers[0] = 5; // First element
numbers[4] = 10; // Last element (index = size-1)
β οΈ Key Points:
- Index Validation:
numbers[5] = 3; // β Undefined behavior (out-of-bounds) - Memory View:
- Contiguous 20 bytes (5 * 4-byte
ints).
- Contiguous 20 bytes (5 * 4-byte
ποΈ Heap-Allocated Arrays
Video Reference: 9:40
int* heapArray = new int[5]; // Allocate
heapArray[2] = 6; // Access
delete[] heapArray; // Must delete!
β οΈ Pitfalls:
- Memory Leaks: Forgetting
delete[]. - No Built-in Size Tracking:
// β WRONG: Returns pointer size (4/8 bytes), not array size int size = sizeof(heapArray) / sizeof(int);
π§ Memory Layout & Pointer Arithmetic
Video Reference: 6:00
int arr[5] = {2, 2, 2, 2, 2};
int* ptr = arr;
// Equivalent to arr[2]
*(ptr + 2) = 6; // β
Offset = 2 * sizeof(int) = 8 bytes
π Visualization:
Memory Address | Value
0x1000 | 2 (arr[0])
0x1004 | 2 (arr[1])
0x1008 | 6 (arr[2])
0x100C | 2 (arr[3])
0x1010 | 2 (arr[4])
π οΈ Best Practices
- Stack vs Heap:
- Prefer stack arrays for local, short-lived data.
- Use heap arrays for large datasets or dynamic lifetimes.
- Size Management:
const int SIZE = 5; int stackArr[SIZE]; for (int i=0; i<SIZE; i++) stackArr[i] = 2;
π C++11 std::array (Safer Alternative)
Video Reference: 15:30
#include <array>
std::array<int, 5> safeArray;
// Features:
safeArray.size(); // β
Returns 5
safeArray.at(2) = 6;// β
Bounds-checked access
β Advantages:
- Built-in size tracking.
- Bounds checking (throws exception if out-of-range).
- Compatible with STL algorithms.
π Key Takeaways
- Raw Arrays:
- Fast but unsafe (no bounds checking).
- Prefer
std::arrayfor safety.
- Heap Arrays:
- Require manual memory management (
new/delete[]).
- Require manual memory management (
- Pointer Arithmetic:
- Understand memory offsets for low-level control.
π Full Video: Arrays in C++
Need to revisit a concept? Jump directly to the video sections with the timestamped links above! π
