Pointer crash

I'm obviously not very good at c++ yet. Having trouble understanding how to use pointers. Making a similar game to tetris right now and a bit confused why what i'm trying here doesn't work. Basically i want controlBoxA to be the same as box.back(). This example crashes my game when i try to access setPosition or getPosition.

Thanks for your time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class cBox{
    public:
    sf::RectangleShape Sprite;
    void setPosition(float x, float y){
        pos.x = x;
        pos.y = y;
    }
    sf::Vector2f getPosition(){
        return pos;
    }
    private:
    sf::Vector2f pos;
};
class cPlayer{
    public:
    cBox *controlBoxA = &box.back();
    std::vector<cBox> box;
}
cPlayer player[2];

cBox boxPush;
player[0].box.push_back(boxPush);

//Later in code
player[0].controlBoxA->setPosition(100, 500);
Last edited on
Be very careful when having pointers to vector elements. The vector stores an array internally (you can get the size of the array by calling .reserve()). If you add more elements than can fit into the array the vector will allocate a new bigger array, copy all the elements from the old array, and then delete the old array. This means that all pointers pointing to elements in the old array will no longer be safe to use because the old array and its elements doesn't exist anymore.

Also note that you should not be calling .back() on an empty vector because it doesn't have an element at the back yet.
Last edited on
Ok. I still don't know why it crashes at runtime though, but i will just use box.back() itself without pointing to it.

Thanks for your help.
I still don't know why it crashes at runtime though
Because when line
cBox *controlBoxA = &box.back(); is executed, it assigns a garbage value to controlBoxA as box vector does not exist yet. And even if it was, it is empty and results on back() are undefined as Peter87 said
Topic archived. No new replies allowed.