在向数组写入数据时发生写访问冲突
Write acess violation while writing data to array
我试图访问构造函数中的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());
相关文章:
- 按字符值访问int数组
- C++ - 循环访问指针数组会导致错误
- 通过unique_ptr访问std::数组
- 为什么我无法访问指向数组中成员函数的指针?
- 在函数 strcpy() 中访问字符数组时出现分段错误
- 在 C++ 中访问 JSON 数组值
- 在C++中访问结构数组中的数据
- C++:在多个线程中访问同一数组/向量的不同单元格是否会产生数据竞赛?
- 是否可以使用宏来访问动态数组或向量中的元素或为其赋值
- 从类访问char数组
- 更快地访问 C++ 数组中的随机元素
- 如何修复访问动态数组中结构中的字符串变量时"segmentation fault (core dumped)"错误
- 在C++中使用 RapidJSON 访问 JSON 数组的字段
- 创建 2D 数组类:如何访问 2D 数组类(如 array[x][y))中的元素
- 通过矢量下标访问 Fortran 数组,相当于 cpp
- 在能够从 Web 浏览器访问大型数组数据的同时存储它的最可行方法是什么?
- 有没有办法使用初始化到第一行的指针访问 2d 数组的第二行?
- 通过C++中的指针访问字符数组
- C++ 如何使用类方法正确访问动态数组元素
- 访问 2D 数组时的读取冲突