Menu
Arrays in C++

Arrays in C++

πŸŽ₯ 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:

  1. Index Validation:
    numbers[5] = 3; // ❌ Undefined behavior (out-of-bounds)  
    
  2. Memory View:
    • Contiguous 20 bytes (5 * 4-byte ints).

πŸ—ƒοΈ Heap-Allocated Arrays

Video Reference: 9:40

int* heapArray = new int[5]; // Allocate  
heapArray[2] = 6;            // Access  
delete[] heapArray;           // Must delete!  

⚠️ Pitfalls:

  1. Memory Leaks: Forgetting delete[].
  2. 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

  1. Stack vs Heap:
    • Prefer stack arrays for local, short-lived data.
    • Use heap arrays for large datasets or dynamic lifetimes.
  2. 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

  1. Raw Arrays:
    • Fast but unsafe (no bounds checking).
    • Prefer std::array for safety.
  2. Heap Arrays:
    • Require manual memory management (new/delete[]).
  3. 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! πŸš€