Dynamic Arrays in C++

In C++, arrays are traditionally created with a fixed size, meaning their size is determined at compile-time. These are referred to as static arrays. However, in many programming scenarios, especially when the number of elements is not known beforehand, dynamic arrays are needed. Dynamic arrays allow for flexibility in memory allocation during runtime, making them a crucial tool in situations where the size of the data cannot be determined in advance.

This post explores dynamic arrays in C++, explaining how they differ from static arrays, how they are created, and how memory is managed. We will also cover how to allocate and deallocate memory for dynamic arrays using the new[] and delete[] operators in C++.

1. Static Arrays vs Dynamic Arrays

1.1 What is a Static Array?

A static array in C++ is an array whose size is determined at compile-time. Once an array is declared, its size cannot be changed during the program’s execution. For example, the following is a static array:

int arr[5] = {1, 2, 3, 4, 5};
  • The size of the array is fixed at 5, and it cannot be resized later in the program.
  • Static arrays are usually stored on the stack memory.
  • Static arrays are generally faster than dynamic arrays because they are contiguous and managed directly by the compiler.

However, static arrays have limitations:

  • The size must be known at compile-time.
  • They cannot be resized dynamically, which makes them unsuitable when dealing with data whose size may change during runtime.

1.2 What is a Dynamic Array?

A dynamic array is an array whose size can be determined and changed during runtime. Dynamic arrays are created using dynamic memory allocation, and the memory is typically allocated from the heap. The key difference between static and dynamic arrays is that the size of dynamic arrays is flexible, and you can allocate more memory as needed or free memory when it is no longer required.

In C++, dynamic arrays are managed using the new[] operator for allocation and the delete[] operator for deallocation.


2. Allocating Memory for Dynamic Arrays

2.1 Using new[] to Create Dynamic Arrays

To create a dynamic array, C++ provides the new[] operator. This operator allocates memory from the heap for an array of the specified type and size. Once the memory is allocated, you can access the elements in the array using the usual indexing notation.

Syntax for new[]:

type* arrayName = new type[arraySize];
  • type refers to the data type of the elements in the array (e.g., int, float, char).
  • arrayName is the pointer that will hold the address of the dynamically allocated array.
  • arraySize is the number of elements in the array.

Example: Allocating and Using a Dynamic Array

#include <iostream>
using namespace std;

int main() {
// Dynamically allocate an array of size 5
int* arr = new int&#91;5];
// Assign values to the array
for (int i = 0; i &lt; 5; i++) {
    arr&#91;i] = i * 10;
}
// Print array elements
for (int i = 0; i &lt; 5; i++) {
    cout &lt;&lt; arr&#91;i] &lt;&lt; " ";
}
cout &lt;&lt; endl;
// Deallocate memory
delete&#91;] arr;
return 0;
}

Explanation:

  1. We dynamically allocate an array of 5 integers using new int[5]. This allocates memory on the heap for an array of integers.
  2. We assign values to the array using a for loop.
  3. After using the dynamic array, we print its elements.
  4. Finally, we release the memory using delete[] arr.

Output:

0 10 20 30 40

This example demonstrates the basic syntax and use of dynamic arrays in C++. The memory for the array is allocated during runtime, which allows you to create arrays whose size is determined by user input or program logic.


3. Deallocating Memory with delete[]

3.1 Why is Deallocation Important?

In C++, memory allocated with new[] is not automatically released when it is no longer needed. This is different from local variables in static arrays, which are automatically deallocated when they go out of scope. If dynamic memory is not properly deallocated, it can lead to memory leaks—situations where memory is allocated but never freed, causing the program to consume more and more memory over time.

To prevent memory leaks, you must use the delete[] operator to deallocate memory that was previously allocated with new[]. This will release the memory back to the operating system.

3.2 Using delete[] to Deallocate a Dynamic Array

After you are done using a dynamic array, you can release the allocated memory by calling delete[] followed by the pointer variable.

Syntax for delete[]:

delete[] pointerName;
  • pointerName is the pointer holding the address of the dynamically allocated array.

Example: Deallocating Memory After Use

In the previous example, we used delete[] arr; to deallocate the memory occupied by the dynamic array arr.

Explanation:

  • The delete[] operator frees the memory block that was allocated for the array. It’s important to call delete[] only on memory that was allocated with new[] to avoid undefined behavior.

4. Resizing Dynamic Arrays

4.1 Reallocating Memory for Dynamic Arrays

In C++, dynamic arrays are fixed in size after allocation. If you need to resize a dynamic array, you cannot directly change its size. Instead, you must allocate a new array of the desired size, copy the elements from the old array to the new array, and then delete the old array.

Example: Resizing a Dynamic Array

#include <iostream>
using namespace std;

int main() {
int* arr = new int&#91;5];  // Dynamically allocate an array of size 5
// Assign values to the array
for (int i = 0; i &lt; 5; i++) {
    arr&#91;i] = i * 10;
}
// Print original array
cout &lt;&lt; "Original Array: ";
for (int i = 0; i &lt; 5; i++) {
    cout &lt;&lt; arr&#91;i] &lt;&lt; " ";
}
cout &lt;&lt; endl;
// Resize the array
int* newArr = new int&#91;10];  // New array with more space
// Copy values from old array to new array
for (int i = 0; i &lt; 5; i++) {
    newArr&#91;i] = arr&#91;i];
}
// Deallocate old array
delete&#91;] arr;
// Assign new values to the resized array
for (int i = 5; i &lt; 10; i++) {
    newArr&#91;i] = i * 10;
}
// Print resized array
cout &lt;&lt; "Resized Array: ";
for (int i = 0; i &lt; 10; i++) {
    cout &lt;&lt; newArr&#91;i] &lt;&lt; " ";
}
cout &lt;&lt; endl;
// Deallocate new array
delete&#91;] newArr;
return 0;
}

Explanation:

  • We start by allocating an array of size 5 and populating it with values.
  • To resize the array, we allocate a new array of size 10 and copy the existing elements into it.
  • After copying, we deallocate the original array using delete[].
  • Finally, we add new values to the resized array and print the result.

Output:

Original Array: 0 10 20 30 40
Resized Array: 0 10 20 30 40 50 60 70 80 90

5. Dynamic Arrays in C++: Best Practices and Common Pitfalls

5.1 Avoiding Memory Leaks

One of the biggest risks when using dynamic arrays in C++ is memory leaks. A memory leak occurs when you allocate memory using new[] but fail to release it with delete[]. Over time, this can consume all available memory and crash your program. Always remember to deallocate memory when it is no longer needed.

5.2 Using std::vector as an Alternative

In modern C++, it is often recommended to use std::vector instead of raw dynamic arrays. The std::vector class from the Standard Template Library (STL) automatically manages memory allocation and deallocation for you. It can also grow or shrink dynamically, unlike static arrays.

Example: Using std::vector

#include <iostream>
#include <vector>
using namespace std;

int main() {
vector&lt;int&gt; vec = {10, 20, 30, 40, 50};
// Print vector elements
for (int i : vec) {
    cout &lt;&lt; i &lt;&lt; " ";
}
cout &lt;&lt; endl;
// Add more elements
vec.push_back(60);
vec.push_back(70);
// Print updated vector
for (int i : vec) {
    cout &lt;&lt; i &lt;&lt; " ";
}
cout &lt;&lt; endl;
return 0;
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *