How to initialize array using user input?

How could I create an array of size n, where n is a int given by the user?

Something like this:
1
2
3
4
5
6
7
8
	
int MAX_SIZE;
cout << "Enter size of array: " << endl;
cin >> MAX_SIZE;

int myArray[MAX_SIZE]; // error: expression must have a constant value

return 0;


Better yet, is there anyway to set the value of a const int to n (the number given to me by user) so that I can use it throughout my program?
Last edited on
How could I create an array of size n, where n is a int given by the user?

By using dynamic arrays:

1
2
cin >> maxSize;
vector<int> myArray(maxSize);

http://www.cplusplus.com/reference/stl/vector/

Better yet, is there anyway to set the value of a const int to n (the number given to me by user) so that I can use it throughout my program?

Sure...

1
2
3
4
int input;
cout << "Enter size of array: " << endl;
cin >> input;
const int maxSize=input;


But you still can't use maxSize for the dimensions of a regular array, since it must be a compile-time constant.
Topic archived. No new replies allowed.