Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'variable name' cannot appear in a constant expression c++

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>
        }
    }
}
like image 208
Captaindh00m Avatar asked Oct 01 '09 03:10

Captaindh00m


1 Answers

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]
like image 141
Mark Rushakoff Avatar answered Oct 23 '22 03:10

Mark Rushakoff