No, itβs not always necessary.
You already know the size at compile time, like:
int arr[100]; // β
works fine, fixed size
Even for small programs where max size is safe (like 1000), this is fine:
int arr[1000];
π₯ Competitive programming / beginner DSA often uses this fixed-size array.
If the user gives input at runtime, and you don't know the size:
int N;
cin >> N;
int arr[N]; // β Not allowed in standard C++
Use dynamic memory:
int* arr = new int[N]; // Allocates N-size array during runtime
Yes, when you use new
, you must manually free memory:
delete[] arr;
If you donβt, it causes a memory leak β bad in long-running programs.
In real-world C++, we use:
#include <vector>
vector<int> arr(N); // Dynamic & auto memory managed β
But for now, you're learning raw arrays β so stick to:
new
+delete[]
if size is dynamic- fixed arrays if size is known or maxed out
Situation | Use What? |
---|---|
Known size (e.g., 100) | int arr[100]; β
|
Unknown size at runtime | int* arr = new int[N]; β
|
Advanced C++ / safer method | vector<int> arr(N); β
|