Skip to content

About Dynamic array and its properties#20

Open
Butcher3Years wants to merge 1 commit intoArrow--Operatorfrom
Dynamic-arrays
Open

About Dynamic array and its properties#20
Butcher3Years wants to merge 1 commit intoArrow--Operatorfrom
Dynamic-arrays

Conversation

@Butcher3Years
Copy link
Copy Markdown
Owner

Basic Dynamic Arrays in C++ – Raw new[] / delete[] (Cherno Style)

Branch: dynamic-arrays-basics
From The Cherno's C++ series — the part where he shows why fixed-size arrays suck and how to make dynamic ones the hard way (before he teaches std::vector).

What We're Doing Here

Fixed-size arrays (int arr[10];) are nice... until you need a size that isn't known at compile time.

That's when we use dynamic arrays with raw new[] and delete[].

Core Concept – Manual Dynamic Array

#include <iostream>

int main() {
    int size;
    std::cout << "How many elements? ";
    std::cin >> size;

    // Allocate dynamic array on heap
    int* arr = new int[size];           // raw allocation – no initialization

    // Fill it (garbage values otherwise!)
    for (int i = 0; i < size; i++) {
        arr[i] = i * 10;
    }

    // Use it
    for (int i = 0; i < size; i++) {
        std::cout << arr[i] << " ";
    }
    std::cout << "\n";

    // MUST delete[] – not delete!
    delete[] arr;                       // wrong: delete arr → undefined behavior
}



The Modern Fix Everyone Should Use
C++


#include <vector>

std::vector<int> arr(size);   // auto allocates, auto deletes, has .size(), bounds-checked in debug

arr.push_back(999);           // grows automatically
std::cout << arr[0] << "\n";  // safe (throws in debug if out of range)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant