Possible Duplicate:
C++ multi dimensional array
I'm trying to create a class that creates an arbitrary sized array of strings based on one of the objects constructor arguments.
Here, the code for the object constructor I'm trying so far:
commandSpec::commandSpec(int numberOfCommands)
{
std::string * commands = new std::string[3][numberOfCommands];
}
I get an error: 'numberOfCommands cannot appear in a constant expression', could someone show me the correct way to specify an array in an object that i d开发者_运维问答ont know the size of until execution.
Thanks, j
This should probably be implemented as a structure and a vector, like this:
struct command {
std::string first;
std::string second;
std::string third;
};
commandSpec::commandSpec(int numberOfCommands)
{
std::vector<command> commands(numberOfCommands);
}
Of course, you should choose appropriate names for the members of command
.
Variable length arrays are allowed only when allocating on heap.
You need to allocate the array in 2 steps - first allocate array with length 3
(from pointers) and then loop through the 3 elements and allocate new string for each.
I'd recommend you to use std::vector
instead.
I would use a std::vector instead, makes life easier:
commandSpec::commandSpec(int numberOfCommands)
{
std::vector<std::vector<std::string>> mystrings(numberOfCommands);
}
Invert the order of the dimensions...
commandSpec::commandSpec(int numberOfCommands)
{
std::string (*commands)[3] = new std::string[numberOfCommands][3];
}
However, I highly recommend you consider using vectors instead.
精彩评论