Dynamic Array:
Array whose size is decided at runtime using new.
int *arr = new int[n];
Example:
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter size: ";
cin >> n;
int *arr = new int[n]; // dynamic array
cout << "Enter elements: ";
for(int i = 0; i < n; i++) {
cin >> arr[i];
}
cout << "Array elements: ";
for(int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
delete arr; // free memory
return 0;
}
Normal Array (Static Array):
An array whose size is fixed at compile time.
int arr[5];
int n;
❌ Error sometime
cin >> n;
int arr[n]; //
This gives error because:
In standard C++, array size must be constant.
n is a variable, so the compiler doesn't allow it (except some compilers like GCC as extension).
Difference:
Feature Normal (Static) Array Dynamic Array
Declaration int arr[5]; int* arr = new
int[n];
Size decided Compile time Runtime
Input using cin cin >> arr[i]; cin >> arr[i];
Memory location Stack Heap
Size flexible? No No (fixed after creation)
Need delete? No Yes (delete[] arr;)
Risk of memory leak No Yes (if not deleted)
Standard C++ Yes Yes