Search code examples
c++arraysmultidimensional-array2dlvalue

Multidimensional array assigning in loop stating: expression must be a modifiable lvalue


So in a class, I have an array like so:

public:
    int playGrid[10][10];//size of the grid, 10x10 or 100 squares

And when I do:

        for (int i = iX1; i < iX2; i++)
        {
            if (i == iX1)
            {
                playGrid[i][iY1] = 4;
            }
        }

This:

playGrid[i][iY1] = 4;

gives me:

expression must be a modifiable lvalue

I'm not sure what I'm doing wrong here. This code is inside one of the methods for the class, so it has access to it. I've looked all over the place, but I was unable to find an example where they were using 2D arrays with a simple integer assignment.

Thank you for your help!

EDIT: More code was requested, so here we go:

void Grid::placeBoat(int iX1, int iY1, int iX2, int iY2) const
{
    if (iX1 != iX2)
    {
        if (iX1 < iX2)
        {
            for (int i = iX1; i < iX2; i++)
            {
                if (i == iX1)
                {       
                    playGrid[i][iY1] = 4;
                }
            }
        }
        else
        {

        }
    }
    else if (iY1 != iY2)
    {

    }
}

and here is the grid class:

class Grid
{
public:
    int playGrid[10][10];//size of the grid, 10x10 or 100 squares
    void drawGrid() const;
    void placeBoat(int, int, int, int) const;
    Grid();
    ~Grid();
};

Solution

  • void Grid::placeBoat(int iX1, int iY1, int iX2, int iY2) const
    

    See the const at the end of the definition? It means that you are allow calling this method when the instance (Grid) is constant.

    Since you allow that call, the entire function body is compiled assuming that this is of type const Grid *.

    You are then trying to change the array, which is a member of the (const) Grid, and hence the compiler error.