Hello! It seems to be a simple question, but I could not find the cause of the bug:

class World{ public: ... Block ***getTerrain(){ return &this->terrain; }; ... private: Block **terrain; } 

There is a class that has an array of objects. When accessing an array inside a class (like this->terrain[i][j].getType() ), everything is fine, but when I try to use the link returned by the getTerrain function ( this->world->getTerrain()[i][j]->getType() ), a segmentation error occurs. What is the problem?

By the way, when I refer to null elements ( this->world->getTerrain()[0][0]->getType() ), everything goes fine.

    1 answer 1

    Your code does not do the same thing.

    In the first case, you access the object

     terrain[i][j] 

    in the second - to

     *((&terrain)[i][j]) 

    The first from the address pointed to by terrain moves to i * sizeof(Block*) , finds the pointer there, and moves from it to j * sizeof(Block) .

    The second one from the address pointed to by terrain moves to i * sizeof(Block**) , finds the pointer there, and moves from it to j * sizeof(Block*) .

    Most likely, sizeof(Block**) and sizeof(Block*) are equal (because the pointer to the data), but sizeof(Block*) and sizeof(Block) are not.

    Try this:

     Block** terrain = *(this->world->getTerrain()); terrain[i][j].getType(); 

    Well, or you can remake the getTerrain function getTerrain that it does not return a double pointer, not triple.

    • How, then, should the array be accessed? - user26699
    • @reload: Added the answer. - VladD 2:44 pm
    • Thank. But in that case, the changes in the array will not be visible from the class, right? - user26699
    • @reload: No, why not? Only if you want to change the terrain field itself, it will not be visible, since you get a copy of the terrain . And the values ​​indicated by terrain are the same in both cases. Try it! - VladD 2:46 pm
    • Hmm ... worked! I never would have thought ... Thank you! - user26699