您好我最近使用过DirectX9而且我遇到了这个错误。虽然它与DirectX无关。这就是我所拥有的。
struct D3DVertex
{
float x, y, z;
DWORD Color;
};
int main()
{
D3DVertex *TestShape = new D3DVertex();
TestShape[0].x = 0.0f;
TestShape[0].y = 2.0f;
TestShape[0].z = 0.5f;
TestShape[0].Color = 0xffffffff;
TestShape[1].x = -2.0f;
TestShape[1].y = -2.0f;
TestShape[1].z = 0.5f;
TestShape[1].Color = 0xffffffff;
TestShape[2].x = 2.0f;
TestShape[2].y = -2.0f;
TestShape[2].z = 0.5f;
TestShape[2].Color = 0xffffffff;
return 0;
}
当我运行它时,它会给我一个运行时错误,说明这一点。
Windows has triggered a breakpoint in x.exe.
This may be due to a corruption of the heap, which indicates a bug in x.exe or any of the DLLs it has loaded.
This may also be due to the user pressing F12 while x.exe has focus.
The output window may have more diagnostic information.
但是当我走开这条线TestShape[2].z = 0.5f;
时,错误消失了。
为什么会发生这种情况,我该如何解决它。请帮忙。
答案 0 :(得分:4)
您在内存中创建了一个对象:
D3DVertex *TestShape = new D3DVertex();
然后你正在访问它,就像它是一个数组
TestShape[x] ...
这就是问题所在,你没有阵列。你有一个对象。
创建一个数组:
D3DVertex *TestShape = new D3DVertex[3];
现在您有3个D3DVertex
类型的对象。
要记住的重点是指针不是数组。只有当你将它作为参数传递给函数时,数组才会将衰减成为指针。然后你得到一个指向数组中第一个元素的指针。
更好的是,使用std::vector<D3DVertex> TestShape;
而不用担心处理指针。
D3DVertex foo; //create object.
TestShape.push_back(foo); //add it to your vector.
您可以使用operator[]
访问您的向量以进行未经检查的访问权限,或使用at(index)
进行边界检查访问
D3DVertex f = TestShape[0]; //Get element zero from TestShape.
如果你想浏览向量并查看每个元素:
for (std::vector<D3DVector>::iterator it = TestShape.begin(); it != TestShape.end(); ++it) // loop through all elements of TestShape.
{
D3DVector vec = *it; //contents of iterator are accessed by dereferencing it
(*it).f = 0; //assign to contents of element in vector.
}