Computer Science Canada

User defined arrays?

Author:  AnubisProgrammer [ Fri Mar 17, 2006 10:51 am ]
Post subject:  User defined arrays?

I'm writing a program for class, and I'm trying to make an array, but the array has to be defined by the user. So I tried making it like this:

int array[n]

then defined "n" later in a user input. Apparently that doesn't work. I get three errors:

error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0
error C2133: 'number' : unknown size


How can I make it so the user defines the size of the array?

Author:  md [ Fri Mar 17, 2006 11:13 am ]
Post subject: 

you can do it rather easily with malloc/new (depending on C/C++). But seeing as dynamic memory allocation is usually not taught at all; or if it is not until the very end of the year I'm guessing this is one of those cases where you are given a maximum size of some kind. That was you can just declate the really big array and have another varaible to keep track of the upper bound.

Author:  wtd [ Fri Mar 17, 2006 11:28 am ]
Post subject: 

c++:
int array_size;

cout << "Max array size? ";
cout.flush();
cin >> array_size;

int *array = new int[array_size];

// do something with array

// and then when you're done...
delete [] array;

Author:  AnubisProgrammer [ Mon Mar 20, 2006 3:05 pm ]
Post subject: 

Yup yup, that worked nicely. Thanks!


: