views:

2946

answers:

1

Anyone have any clue what this error might actually mean? I'm tripping on a bit of code that can't seem to get around it. I've tried it with just h*2 instead of hprime, and just w*2 instead of wprime. Every time I get the same compiler (g++ compiler) error of :

grid.cpp: In constructor ‘Grid::Grid(int, int)’:

grid.cpp:34: error: ‘hprime’ cannot appear in a constant-expression

(the compiler doesn't always say hprime, it will say whatever variable is there, be it h or hprime or width). Any help would be greatly appreciated!

class Grid
{
    public:
    Grid(int x, int y);
    ~Grid();

    void addObstacle(int w, int h);
    void toString();

    int** grid;
    int height;
    int width;

};

Grid::Grid(int w, int h)
{
    width = w;
    height = h;
    const int hprime = h*2;
    const int wprime = w*2;
    grid = new int[wprime][hprime];

    for(int x=0;x<wprime;x++) {
        for (int y=0; y<hprime;y++) {
            grid[x][y] = 0;<br>
        }
    }
}
+5  A: 

You can't use new to allocate a two-dimensional array, but you can change the offending line like this:

  grid = new int*[wprime];
  for (int i = 0 ; i < wprime ; i++)
      grid[i] = new int[hprime];

If it doesn't have to be multidimensional, you can do:

grid = new int[wprime*hprime];

and just index it like

grid[A*wprime + B]

where you would normally index it like

grid[A][B]
Mark Rushakoff
Worked, thank you.
Captaindh00m
You can sort-of use new to allocate a two-dimensional array, but only the first dimension is variable. `new Grid[i][3]` is fine, `new Grid[3][i]` is not. So really you're allocating a one-dimensional array of Grid[3], but then that's all a C/C++ multi-dimensional array is.
Steve Jessop