Advantage of dynamic array

Hiii people.

I remember in the lecture my instructor said some advantages of dynamic array but wasn't in detail and I couldn't recall it now. So apart from preventing wasting memory space, what are other advantages of dynamic array? I vaguely remember she said something like if you have an array arr[size] when it is a static array you cannot do arr=something, but when it is a dynamic one you can... thanks everyone.
As its name suggests, dynamic arrays allow you to have variable sizes at run time. For example,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int main()
{
    std::cout << "enter amount of numbers to sum: ";
    int count{}; std::cin >> count;

    int* nums{ new int[count]{} };
    for( int i{}; i < count; i++ ) {
        std::cout << "enter #" << i + 1 << ": ";
        std::cin >> nums[i];
    }
    std::cout << '\n';

    int sum{};
    for( int i{}; i < count; i++ ) sum += nums[i];

    std::cout << "sum = " << sum << '\n';
    
    delete[] nums;
}


enter amount of numbers to sum: 3
enter #1: 1
enter #2: 2
enter #3: 3

sum = 6


Though, it is highly recommended to use std::vector for dynamic arrays, as you may forget to delete the allocated memory or accidentally assign arr to another dynamically allocated array, forgetting to deallocate the original memory.

So apart from preventing wasting memory space, what are other advantages of dynamic array?

What do you mean by wasting memory space? Dynamic arrays have to be allocated in memory as well.
large data stores that change in side have downsides also. C++ demands that arrays and vectors, as well as blobs allocated with new and more to be one solid block of memory, not fragmented. If you change the size frequently, you generally have a behind the scenes copy of every data item. It basically allocates a new block of the new size, and moves the old block's data over to it, then kills off the old block.

That can be worked around, of course. You can allocate large blocks at a time, doing the copy operations infrequently, for example. Its more of a warning to avoid changing the size frequently, is all.

Also, memory waste isn't on the order of megabytes anymore, really. My home pc has 32 GB of ram. Production computers at your job will have even more; our sandbox where I work has 96 GB. A lot of algorithms suffer the "time space tradeoff" where you can use more time and less space, or more space and less time. Anyway, just think about things as you write your software. If you need a 10 MB array of doubles, allocate it and don't sweat whether it needs to grow on demand or not. If your software is going to need to burn out more than 10% of the memory on the system for an extended duration, then you need to start thinking about conservation. That's over 3GB in use at once for more than a few min on modern computers, though. That's a lot of space for most programs.



Topic archived. No new replies allowed.