0

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 dont know the size of until execution.

Thanks, j

Community
  • 1
  • 1
jonathan topf
  • 7,417
  • 13
  • 53
  • 81
  • And God (or was it Stroustrup ?) created the `vector`. – Matthieu M. Jun 09 '11 at 12:20
  • so is it bad form to add an array on the heap like that (if i fix the syntax)? I thought that as the size wont change after its created i wouldnt need the featres that a vector would give me, i just need a simple array thats size will be defined at runtime but will still be fixed when it is defined. – jonathan topf Jun 09 '11 at 12:33

4 Answers4

2

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.

Björn Pollex
  • 72,744
  • 28
  • 189
  • 274
1

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.

Kiril Kirov
  • 36,509
  • 22
  • 109
  • 183
0

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.

Andrew White
  • 51,542
  • 18
  • 111
  • 135
0

I would use a std::vector instead, makes life easier:

commandSpec::commandSpec(int numberOfCommands)
{
    std::vector<std::vector<std::string>> mystrings(numberOfCommands);
}
Tony The Lion
  • 59,704
  • 62
  • 233
  • 403
  • I think you have the dimensions in the wrong order. It should be 3 first, then numberOfCommands. – Beta Jun 09 '11 at 12:25