我试图在构造函数中访问 SDL_Rect*
数组,但每次我这样做时都会遇到 Write access violation
。我尝试了多种解决方案,但没有一个对我有用。
我目前拥有的:我制作了一个struct
数组:SDL_Rect* rects[50]
。
然后我尝试使用
访问数据this->rects[index]->x = x;
这会导致写访问冲突。
我还尝试删除数组 (SDL_Rect* rects
) 并使用访问数据
rects->y = y;
但这也导致了写访问冲突。
一个数组会很棒,但是每次我尝试我都会得到前面提到的异常,这是无法实现的吗?
rect.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];
也就是说,我不会使用数组/指针,而是使用 std::vector<SDL_Rect>
.
关于c++ - 将数据写入数组时写访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38094166/