Kiarash Kanani
Kiarash Kanani

Reputation: 3

I have a question about dynamic allocation of memory in c++

I'm new to c++ and I can't understand something in dynamic allocation. why does the following program build but gives an error and stops?

#include <iostream>
using namespace std;

int main()
{

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


    cout << "enter the size of array" << endl;
    cin >> amount;




    for(int i = 0; i < amount ; i++)
    {
        cout << "enter the " << i + 1 << " number" << endl;
        cin >> p[i];
    }

    for(int i = 0; i < amount ; i++)
    {
        cout << "number " << i + 1 << " is : " << p[i] << endl;
    }

    delete []p;


}

Upvotes: 0

Views: 58

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 598154

You are trying to use amount before you have assigned any value to it. You need to read the user's input for amount first, THEN allocate using it. Not the other way around.

#include <iostream>
using namespace std;

int main()
{
    int amount;

    cout << "enter the size of array" << endl;
    cin >> amount;

    int *p = new int[amount];

    for(int i = 0; i < amount ; i++) {
        cout << "enter the " << i + 1 << " number" << endl;
        cin >> p[i];
    }

    for(int i = 0; i < amount ; i++) {
        cout << "number " << i + 1 << " is : " << p[i] << endl;
    }

    delete[] p;
}

Upvotes: 5

Related Questions