Click to See Complete Forum and Search --> : const int and delcaration of an array
SGSpecialK
February 18th, 2003, 11:56 PM
I'm writing a program and it has to do with an array. I have to let the user decide the size of the array,but when I code this,
int combined;
cin >> combined;
const int SIZE= combined;
int array[SIZE];
the compiler gives me an error. I also tried this
const int SIZE;
cin >> SIZE;
int array[SIZE];
How can I declare and array of a size decided by the user?
Kheun
February 19th, 2003, 12:18 AM
Since the size is varying, you can't create the array on the stack. Try using "new" instead.
int size;
cin >> size;
int* array = new int[size];
delete []array;
SGSpecialK
February 19th, 2003, 12:23 AM
THank you so much. It worked! :D
Kheun
February 19th, 2003, 12:27 AM
You're welcome. :)
Paul McKenzie
February 19th, 2003, 01:56 AM
Originally posted by SGSpecialK
I'm writing a program and it has to do with an array. I have to let the user decide the size of the array,but when I code this,
int combined;
cin >> combined;
const int SIZE= combined;
int array[SIZE];
the compiler gives me an error. I also tried this
const int SIZE;
cin >> SIZE;
int array[SIZE];
How can I declare and array of a size decided by the user?
#include <vector>
#include <iostream>
using namespace std;
//...
int nSize;
cin >> nSize;
vector<int> array( nSize ); // declare an array with variable size
To declare a dynamic array in C++, you always go for the vector<> class unless you have a compelling reason to use new[] and delete[].
Regards,
Paul McKenzie
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.