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

2
  • And God (or was it Stroustrup ?) created the vector. Commented Jun 9, 2011 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. Commented Jun 9, 2011 at 12:33

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

0

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

commandSpec::commandSpec(int numberOfCommands)
{
    std::vector<std::vector<std::string>> mystrings(numberOfCommands);
}

1 Comment

I think you have the dimensions in the wrong order. It should be 3 first, then numberOfCommands.
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.

2 Comments

This doesn't work. It just isn't how C++ handles arrays.
@Beta: sorry, forgot the lhs array part; this should work now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.