Topic 44 of 83
Dynamic Arrays
Overview
Standard arrays require their size to be known at compile-time. Dynamic arrays use `new[]` to allow sizes determined at runtime based on user input.
Syntax
cpp
int size;
cin >> size;
// Allocate array on the heap
int* arr = new int[size];
// Free the array using delete[]
delete[] arr;Common Pitfalls
- In modern C++, you should almost never use raw dynamic arrays (`new[]`). Use `std::vector` instead, which handles all memory management automatically.
Interview Tips
- If you use `new[]` to allocate, you MUST use `delete[]` to free. Using standard `delete` on an array only frees the first element and corrupts memory.
Real-World Example
Creating an array whose size is defined by the user.
example
cpp
#include <iostream>
using namespace std;
int main() {
int numStudents;
cout << "How many students? ";
cin >> numStudents;
// Dynamic allocation
int* scores = new int[numStudents];
for (int i = 0; i < numStudents; i++) {
scores[i] = 100; // Everyone gets 100!
}
// Cleanup
delete[] scores;
return 0;
}