Samuel
Samuel

Reputation: 640

understanding the use of dynamic memory allocation in c++

consider this program:

#include <iostream>
using namespace std;

int main ()
{
    int i;
    cout << "How many numbers would you like to type? ";
    cin >> i;

    int * p;
    p= new int[i];

    cout << "Enter the numbers: \n";

    for (int n=0; n<i; n++)
      cin >> p[n];

    cout << "You have entered: ";

    for (int n=0; n<i; n++)
      cout << p[n] << ", ";

    delete[] p;

    return 0;
}  

and this one:

#include <iostream>

using namespace std;

int main()
{
    int num;

    cout << "How many numbers would you like to type? ";
    cin >> num;

    int arr[num];

    cout << "Enter the numbers: \n";

    for (int a = 0; a <num; ++a)
        cin >>arr[a];

    cout << "You have entered: ";  

    for (int a = 0; a <num; ++a)
        cout <<arr[a]<< ", ";
    return 0;
}

Both programs are accomplishing the same task and -to me- the latter is a lot
easier to understand than the former. And now my question is why do we need dynamic memory allocation anyway?

Upvotes: 0

Views: 90

Answers (2)

Ben
Ben

Reputation: 8905

Consider what happens if this array you create needs to survive past the scope of the function it is created in. For example, if this isn't the main() function, but some helper function that returns the memory to main. Or perhaps you have no way of knowing in advance, how many objects to create. For example, you could be maintaining a tree or graph-based data structure based on dynamic real-time data.

In the simple example you give, you're correct: dynamic allocation of an array on the heap is probably a waste and can easily lead to problems like memory leaks if done poorly (although there are ways around that, like using modern RAII techniques for all your allocation). But more complicated scenarios are made much simpler if dynamic memory is available.

Upvotes: 0

jrok
jrok

Reputation: 55395

When num is not a compiler time constant, int arr[num]; is a VLA (variable length array) and that's not standard C++. It's a language extension offered by some compilers (you're using G++, I assume).

Something that's also easy to use and doesn't require you to use raw pointers and deal with manual dynamic allocations is std::vector:

int i;
cout << "How many numbers would you like to type? ";
if (!(cin >> i)) {   // error checking is important
    cout << "Not a number, abort!\n";
    return 1;
}

std::vector<int> numbers(i);

cout << "Enter the numbers: \n";

for (int a = 0; a < i; ++a)
    cin >> numbers[a];

Upvotes: 1

Related Questions