0% found this document useful (0 votes)
2 views2 pages

Dynamic Array

The document explains the concept of dynamic and static arrays in C++. A dynamic array's size is determined at runtime using 'new', while a static array's size is fixed at compile time. It also highlights the differences between the two types, including memory allocation, flexibility, and the need for memory management.

Uploaded by

sahilkashyap2122
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Dynamic Array

The document explains the concept of dynamic and static arrays in C++. A dynamic array's size is determined at runtime using 'new', while a static array's size is fixed at compile time. It also highlights the differences between the two types, including memory allocation, flexibility, and the need for memory management.

Uploaded by

sahilkashyap2122
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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

You might also like