Array size defined with a variable.

Started by
7 comments, last by GameDev.net 18 years, 6 months ago
How can I define the size of an array through a variable. Eg;
int size = 256;
string array[size];
except that doesn't work, so how can i do it?
If it's possible for us to conceive it, than it must be possible.
Advertisement
You need to dynamically create the array, that is:


int size = 256;string *array = new string[size];// ...// cleanupdelete [] array;

[edit] But since you are using string (I assume STL), why not use vector as well (edit3: see Enigma's post for an example)?
[edit2] If size never changes, you can make it const and it will work in your original code.

jfl.
std::vector< std::string > array(256) or boost::array< std::string, 256 > array.

EDIT: Sorry, boost::array won't work for a dynamic size. I was thinking there was a dynamic but non-resizeable array type in boost, but it appears that there isn't. Instead you can just use boost::shared_array< std::string > array(new std::string[size]) or boost::scoped_array< std::string > array(new std::string[size]).

Enigma

[Edited by - Enigma on October 9, 2005 6:27:51 PM]
ok thanks
If it's possible for us to conceive it, than it must be possible.
I think gcc allows it anyway. It's certainly not standard in C++ but it is in C99 (though I'm guessing from the string declaration you aren't using that).
in c++ if you declare size as "const" it should allow that code
Also instead of using int whynot use unsigned int?

using namespace std ;typedef unsigned int UINT ;const UINT SIZE = 100 ;vector< string > my_array( SIZE ) ;
Declaring an array with a constant size (be it a literal or symbolic constant) isn't declaring an array with the size defined by a variable.
"Walk not the trodden path, for it has borne it's burden." -John, Flying Monk
C99 allows this, they're called "Variable Length Arrays" or VLAs for short.

This also brings up a difference between C and C++ that's perhaps significant in this context. Consider:
int main(void) {
const int size = 10;
int foo[size];
return 0;
}
In C99 foo is a VLA, in C++ foo is an array, and in C89 this is illegal.
const means "constant" in C++ and "read-only" in C.

Also, if you want a non-standard option, alloca() might be helpful depending on why you need a variable length array.

This topic is closed to new replies.

Advertisement