-4

嗨,我最近使用 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;,错误就消失了。为什么会发生这种情况,我该如何解决。请帮忙。

4

1 回答 1

4

您正在内存中创建一个对象:

D3DVertex *TestShape = new D3DVertex();

然后你像访问数组一样访问它

TestShape[x] ...

这就是问题所在,您没有数组。你有一个对象。

创建一个数组:

D3DVertex *TestShape = new D3DVertex[3];

现在你有 3 个类型的对象D3DVertex

要记住的重要一点是指针不是数组。唯一获得指针的情况是,当您将数组作为参数传递给函数时,该数组已衰减为指针。然后你得到一个指向数组中第一个元素的指针。

更好的是,使用 astd::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.
}
于 2013-03-10T12:42:35.480 回答