Dynamic arrays plays a crucial role in modern programming, providing flexibility and effiecieny when dealing with data structures in C++. Unlike static arrays, dynamic arrays allow you to allocate and deallocate memory at runtime, making them a powerful tool for handling variable-sized datasets.
What is Dynamic Array?
A dynamic array in C++ is an array-like structure whose size can be changed during runtime. It is created using pointers and memory allocation functions, such as new and delete or malloc and free. Unlike static arrays, which have a fixed size determined at compile time, dynamic arrays offer the flexibility to resize based on the program's requirement.
Creating a Dynamic Array
To create a dynamic array in C++, you use pointers and allocate memory on the heap. Here's a simple example:
#include <iostream>
int main() {
// Declare a pointer to an integer
int *dynamicArray;
// Dynamically allocate memory for an array of size 5
dynamicArray = new int[5];
// Access and manipulate elements
dynamicArray[0] = 1;
dynamicArray[1] = 2;
// ...
// Deallocate memory to prevent memory leaks
delete[] dynamicArray;
return 0;
}
In this example, new int[5] allocates memory for an integer array of size 5 on the heap. The delete[] statement is crucial to free up the allocated memory when it is no longer needed.
Resizing a Dynamic Array
One of the key advantages of dynamic arrays is their ability to resize. However, resizing involves creating a new array, copying the elements from the old array to the new one, and deallocating the old array. Here's a basic example:
#include <iostream>
int main() {
// Declare a pointer to an integer
int *dynamicArray;
// Dynamically allocate memory for an array of size 5
dynamicArray = new int[5];
// Resize the array to 10 elements
int *newDynamicArray = new int[10];
// Copy elements from the old array to the new one
for (int i = 0; i < 5; ++i) {
newDynamicArray[i] = dynamicArray[i];
}
// Deallocate the old array
delete[] dynamicArray;
// Update the pointer to point to the new array
dynamicArray = newDynamicArray;
// Access and manipulate elements in the resized array
dynamicArray[5] = 6;
// ...
// Deallocate memory when done
delete[] dynamicArray;
return 0;
}
It's important to note that manually resizing arrays can be error-prone and cumbersome. C++ provides a more convenient alternative: std::vector container, which is essentially a dynamic array with built-in resizing capabilities, we will discuss about it in next chapter.
Leave a comment
Your email address will not be published. Required fields are marked *


