user2852158
user2852158

Reputation: 1

How do I make an array have size of a value inputted by a user? (C++)

Here is what I am basically trying to do

cout<<"Enter size of array"<<endl;
cin>>size;

int my_array[size];

The compiler complains that size must be constant.

Upvotes: 0

Views: 67

Answers (2)

Ebin
Ebin

Reputation: 43

I think you can use the new keyword here to allocate memory dynamically just modify your code like this and it should be fine

int *my_array;

 cout<<"Enter size of array"<<endl;
 cin>>size;
 my_array=new int[size];

Upvotes: 1

Mike Seymour
Mike Seymour

Reputation: 254431

Indeed, arrays must have constant size. You'll want a dynamic array:

std::vector<int>(size);

Upvotes: 2

Related Questions