Array size defined with a variable.

This topic is 4518 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

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?

Share on other sites
You need to dynamically create the array, that is:

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

 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.

Share on other sites
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

Share on other sites
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).

Share on other sites
in c++ if you declare size as "const" it should allow that code

Share on other sites
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 ) ;

Share on other sites
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.

Share on other sites
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.