Powered by AI
Bing
A dynamic array is a resizable array that can grow or shrink in size during
runtime. It is an array that can change its size during the execution of a
program. The dynamic array is a variable-size list data structure that grows
automatically when we try to insert an element if there is no more space left
for the new element. It allows us to add and remove elements and allocates
memory at runtime using the heap .
Here's an example of how a dynamic array works in C++:
#include <iostream>
using namespace std;
int main() {
int *arr = new int[3];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
cout << "Elements of the array: ";
for (int i = 0; i < 3; i++) {
cout << arr[i] << " ";
}
delete[] arr;
return 0;
}
In this example, we create a dynamic integer array named arr with an initial
size of 3. We then assign values to the first three elements of the array using
the subscript operator []. Finally, we print the elements of the array using a for
loop and deallocate memory using the delete[] operator .
I hope this helps!