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,897
  • 17
  • 55
  • 85
  • 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
  • 75,346
  • 28
  • 201
  • 283
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
  • 37,467
  • 22
  • 115
  • 187
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
  • 52,720
  • 19
  • 113
  • 137
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
  • 61,704
  • 67
  • 242
  • 415
  • I think you have the dimensions in the wrong order. It should be 3 first, then numberOfCommands. – Beta Jun 09 '11 at 12:25