在向数组写入数据时发生写访问冲突

Write acess violation while writing data to array

本文关键字:访问冲突 数组 数据      更新时间:2023-10-16

我试图访问构造函数中的SDL_Rect*数组,但每次我都得到Write access violation。我尝试了多种解决方案,但都不适合我。

我现在拥有的:我做了一个struct: SDL_Rect* rects[50]的数组。

然后尝试使用

访问数据
this->rects[index]->x = x;

这会导致写访问冲突。

我还试图删除数组(SDL_Rect* rects)并使用

访问数据
rects->y = y;

但是这也会导致写访问冲突。

数组将是美妙的,但每次我尝试我得到前面提到的异常,这是不可实现的吗?


rects.cpp:

namespace SDLGamecore {
namespace graphics {
    Rects::Rects(int x, int y, int w, int h)
    {
        rects->x = x; //Exception thrown: write access violation.
        rects->y = y;
        rects->w = w;
        rects->h = h;
        rectsSize += 1; //this works...
    }
    Rects::~Rects()
    {
        delete[] rects;
    }
    SDL_Rect* Rects::getRects()
    {
        return rects;
    }
    int Rects::getRectsSize()
    {
        return rectsSize;
    }
}}

rects.h:

namespace SDLGamecore { namespace graphics {
    class Rects
    {
    private:
        //SDL_Rect rects[50];
        SDL_Rect* rects;
        int rectsSize = 0;
    public:
        Rects(int x, int y, int w, int h);
        ~Rects();
    public:
        SDL_Rect* getRects();
        int getRectsSize();
    };
}}
typedef struct SDL_Rect
{
    int x, y;
    int w, h;
} SDL_Rect;

您忘记在构造函数中分配rects,这只是一个指针:

rects = new SDL_Rect[50];

也就是说,我不会使用数组/ptr,而是使用std::vector<SDL_Rect>

您不能使用构造函数将SDL_Rect"添加"到rects中,因为构造函数创建了一个新的rects。实际上,我不认为你真的需要一个自定义结构来保存SDL_Rect的数组/列表,只需使用std::vector,例如在你的main中:

std::vector<SDL_Rect> rects;
rects.push_back({1, 1, 4, 5}); // Add a SDL_Rect with x=1, y=1, w=4, h=5
rects.push_back({1, 4, 2, 3});
然后,当你需要调用render:
SDL_RenderDrawRects(rendered, rects.data(), rects.size());

如果你真的想使用自定义结构,例如Shape,那么在内部使用std::vector:

class Shape {
    std::vector<SDL_Rect> _rects;
public:
    Shape () { }
    void addRect (int x, int y, int w, int h) {
        _rects.push_back({x, y, w, h});
    }
    const std::vector<SDL_Rect>& getRects () const { return _rects; }
};

然后在main:

Shape shape;
shape.addRect(1, 1, 4, 5);
shape.addRect(1, 4, 2, 3);
SDL_RenderDrawRects(renderer, shape.getRects().data(), shape.getRects().size());

或者你可以直接让Shape继承std::vector<SDL_Rect>:

class Shape: std::vector<SDL_Rect> {
    void addRect (int x, int y, int w, int h) {
        this->push_back({x, y, w, h});
    }
};
Shape shape;
shape.addRect(1, 1, 4, 5);
shape.addRect(1, 4, 2, 3);
SDL_RenderDrawRects(renderer, shape.data(), shape.size());