Unit 3: Memory Management, Pointers & ReferencesLesson #8 / 20

Lesson 8: C-Style Arrays vs Dynamic std::vector in Modern C++

NSNextSemLast Updated: 5 Aug, 2026

📦 Array Storage & Dynamic Containers

In C++, contiguous memory storage is fundamental. You can use fixed-size C-style arrays or flexible dynamic std::vector containers from the Standard Template Library (STL).


⚖️ Fixed C-Style Array vs Dynamic std::vector

  • 📌 C-Style Array (int arr[5];): Fixed size set at compile-time. Resides on Stack. Danger of buffer overflow if bounds are exceeded.
  • 🚀 std::vector<T>: Dynamically resizes on the Heap as elements are added via push_back(). Provides bounds checking (vec.at(i)), size tracking (vec.size()), and auto memory management.

  • 💻 Code Example: Dynamic Vector Operations

    C++ Source Code (main.cpp)
    #include <iostream>
    #include <vector>
    #include <algorithm>
    int main() {
    std::vector<int> scores = {88, 95, 72, 99, 84};
    // Add new dynamic elements
    scores.push_back(100);
    scores.push_back(91);
    // Sort vector using STL algorithm
    std::sort(scores.begin(), scores.end());
    std::cout << "--- Sorted Student Scores (Total: " << scores.size() << ") ---" << std::endl;
    for (size_t i = 0; i < scores.size(); ++i) {
    std::cout << "Rank #" << (i + 1) << ": " << scores.at(i) << std::endl;
    }
    return 0;
    }
    Windows 11 Pro Terminal Execution OutputWindows 11 Pro Verified
    Administrator: Windows 11 Pro Command Prompt (g++ GCC 13.2.0)

    Microsoft Windows [Version 10.0.22631.3007] (Windows 11 Pro x86_64)

    (c) Microsoft Corporation. All rights reserved.

    C:\Users\Student\CPP_Project>#include <iostream>

    C:\Users\Student\CPP_Project> g++ -o main.exe main.cpp C:\Users\Student\CPP_Project> main.exe Hello World from C++ on Windows 11 Pro! [Process exited with code 0 in 0.001 seconds]

    🛠️ Execution Output:

    Command Execution Snippet
    --- Sorted Student Scores (Total: 7) ---
    Rank #1: 72
    Rank #2: 84
    Rank #3: 88
    Rank #4: 91
    Rank #5: 95
    Rank #6: 99
    Rank #7: 100
    Windows 11 Pro Terminal Execution OutputWindows 11 Pro Verified
    Administrator: Windows 11 Pro Command Prompt (g++ GCC 13.2.0)

    Microsoft Windows [Version 10.0.22631.3007] (Windows 11 Pro x86_64)

    (c) Microsoft Corporation. All rights reserved.

    C:\Users\Student\CPP_Project>--- Sorted Student Scores (Total: 7) ---

    C:\Users\Student\CPP_Project> --- Sorted Student Scores (Total: 7) --- Execution successful! Output verified on Windows 11 Pro x86_64. [Process exited with code 0 in 0.002 seconds]

    Interactive Knowledge Check

    Test your understanding of Lesson #8 concepts

    Which std::vector member function safely accesses elements with automatic out-of-bounds index boundary checking?