Why use a dynamic array instead of a regular array?

Viewed 314

The following code is used to demonstrate how to insert a new value in a dynamic array:

#include <iostream>

int main()
{
    int* items = new int[5] {1, 2, 3, 4, 5}; // I have 5 items

    for (int i = 0; i < 5; i++)
        std::cout << items[i] << std::endl;

    // oh, I found a new item. I'm going to add it to my collection.
    // I do this by
    // (1) allocating a bigger dynamic array
    // (2) copying the existing elements from the old array to the new array
    // (3) deleting the old array, redirecting its pointer to the new array
    int* items_temp = new int[6];
    for (int i = 0; i < 5; i++)
       items_temp[i] = items[i];
    items_temp[5] = 42;
    delete[] items;
    items = items_temp;

    for (int i = 0; i < 6; i++)
        std::cout << items[i] << std::endl;

    delete[] items;
}

I am confused about the necessity of using it over a regular array. Can't I just do the same thing with a regular array? Basically, you just define a new array with a larger size and move elements in the previous array to this new array. Why is it better to use a dynamic array here?

2 Answers

You are right, the example you are looking at isn't very good at demonstrating the need for dynamic arrays, but what if instead of going from size 5->6, we had no idea how many items we found until we need to add until the code is actually running?

Regular arrays need to be constructed with their size known at compile time

int foo [5] = { 16, 2, 77, 40, 12071 };

But dynamic arrays can be be assigned as size at runtime

int* Arrary(int size) {
    return new int[size];
}

So if you don't know the size of your array, or it may need to grow/shrink you need to use a dynamic array (or better yet just use a std::vector).

Suppose you want to do what you mentioned a multiple times.

for(int i = 0; i < some_val; ++i)
{
    int val_to_add;
    std::cin >> val_to_add;

    int* new_arr = new int[old_size + 1]; // the value is suppsoed to be big in order to indicate that it takes much memory.
    copy_old_to_new(new_arr, old_arr); //some function which does the copying. 

    new_arr[old_size + 1] = val_to_add;
    delete[] old_arr;
    old_arr = new_arr;
}

Now think about what would happen if we tried to do the same with static arrays.

  1. We wouldn't be able to remove the memory allocated by the old_arr, and the program would use a lot of memory.
  2. We wouldn't be able to construct an array which would be accessible outside the loop, which, obviously, is not intended.

In your example it is not much clear how the usage of dynamic arrays would make use in your intention. So if you feel you could do the same without dynamic arrays, do it without them.

Related