variable size arrays

Apr 25, 2008 at 12:24pm
how can i write a variable sized array...for instance:
1
2
3
int x;
in >> x;
int array[x];

now, that wont compile on my compiler (Borland turbo c++). can anyone help me and tell me how i can create an array that is of a variable size?
my compiler gives the error that it cant convert int into int* (i.e, it cant convert the x into the array[x])
thanks for the help
Apr 25, 2008 at 12:39pm
In the documention(on this site) there is a chapter about dynamic array allocation. You could also use a vector instead.
Apr 25, 2008 at 12:44pm
I believe you might be using an older compiler that does not support variable sized arrays, so you'll need to dynamically create it as Somelauw suggested.

1
2
3
4
5
int x;
in >> x;
int* array = new int[ x ];
// use array here ...
delete [] array;
Apr 25, 2008 at 12:46pm
Hi, you will need to use a dynamic array

1
2
3
4
5
int *myArray;                //Declare pointer to type of array
myArray = new int[x];   //use 'new' to create array of size x
myArray[3] = 10;          //Use as normal (static) array
...
delete [] myArrray;       //remeber to free memeory when finished. 


That's the 30s guide to dynamic arrays anyway:-)
Try looking in the tutorial (http://www.cplusplus.com/doc/tutorial/)under 'Dynamic Memory' for more info.

For more sophisicated use of dynamic data structures check the STL container classes (http://www.cplusplus.com/reference/stl/) once you are happy you understand the standard dynamic arrays.
Apr 26, 2008 at 1:55am
thanks for all the help - im using Borland Turbo c++, but possibly using Dev c++ might fix this?
and will using int* array = new int [ x ]; rewrite the original x variable?
Topic archived. No new replies allowed.