0

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;


}
2
  • 1
    amount has undefined value. Also note since c++11 explicit use of new is considered a bad practice. Just use std::vector in this code and ti will handle memory management for you. Commented Aug 10, 2020 at 16:18
  • @MarekR "since c++11 explicit use of new is considered a bad practice" - use of new[] for arrays was discouraged in favor of std::vector long before C++11. Commented Aug 10, 2020 at 17:08

1 Answer 1

5

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.