understand the use of dynamic memory allocation in c ++

advertisements

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?


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];