Luke B.
Luke B.

Reputation: 1288

C++ Losing pointer reference after scope end

I'm getting a really weird error where after I leave the for scope I can't access whatever my pointer was pointing during the loop even if the array holding the objects is declared in the class header.

This is the basic of the code:

Class CTile{ /*Code*/ };

Class CMap  
{  
    public:  
        CTile** tiles;  
        CMap();  
}

CMap::CMap()  
{  
    int lines = 10;
    int cols = 10;
    tiles = new CTile*[lines];  
    for(int i = 0 ; i (lower than) lines;++)  
    {  
        this->tiles[i] = new CTile[cols];  
    }  
    for(int curLine = 0; curLine (lower than) lines ; curLine++)  
        for(int curCol = 0; curCol (lower than) cols; curCol++)  
        {
            CTile me = this->tiles[curLine][curCol];
            me.setType(1);
            //do whatever I need, and inside the loop everything works.  
        }  
    int a = this->tiles[2][2].getType(); // a gets a really weird number 
    this->tiles[2][2].setType(10); // crashes the program

}

Does anyone know what could be wrong?

Upvotes: 3

Views: 1907

Answers (2)

Andy Finkenstadt
Andy Finkenstadt

Reputation: 3587

CTile me = this->tiles[curLine][curCol];

That should be

CTile& me = this->tiles[curLine][curCol];
me.setType(1);

Why? Because you made a copy of CTile, instead of creating a reference to the one in the 2-dimensional array. You might now discover that the crash has moved to the me.setType(1) statement.

Upvotes: 4

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361492

CTile  me = this->tiles[curLine][curCol];

Here is the problem. me is a copy of the original object tiles[curLine][curCol], so whatever you're doing with me isn't reflected in the original object. The orginal object remains unchanged even if you do me.setType(1). I'm sure you didn't want that.

So the fix is : use reference as :

CTile & me = this->tiles[curLine][curCol];
  //  ^ note this
me.setType(1);

Or better yet, you can simply do this:

tiles[curLine][curCol].setType(1); //"this" is implicit!

Upvotes: 4

Related Questions