调试断言失败 - C++
问题描述:
我想在一个struct点一个指针到另一种类型的结构的数组。这里是我的代码:调试断言失败 - C++
struct Mesh
{
long masterRef; // The global fragment number
long polygonCount; // Number of polygons in the mesh
long vertexCount; // Number of verticies in the mesh
Vertex *verti; // Pointer to verticies in the mesh
Poly *poly; // Pointer to polygons in the mesh
float center[3]; // The center of the mesh
bool isVisible; // Is the mesh currently visible?
} typedef Mesh;
struct Region
{
bool hasPoly;
long size1;
long size2;
long size3;
long size4;
long size5;
long size6;
Mesh* meshptr; // the mesh with the polygons for this region
long meshRef;
std::vector<int> visvector;
long regionsVisible;
};
正如你所看到的,我想创建区域结构网格指针。指针将指向网格数组中的Mesh。仅此行导致程序与调试断言失败的消息和崩溃“表达式:无效的空指针”
有谁知道这个问题可能是什么?我会发布调用代码,但它没有它崩溃。
答
我认为你的问题是,你“想有一个结构点的指针结构数组”。要声明一个指向数组的指针,你需要一个稍微不同的语法:Mesh (*meshptr)[array_size];
。由于您的结构立即可用,meshptr
是指向单个对象而不是数组的指针。试图像数组那样使用该指针会导致问题,因为您将直接访问指针后面的内存。这可以解释为什么将指针移动到数据结构的末尾似乎有效。当你这样做的时候,你会破坏结构之后的内存,而不是破坏指针后面的结构成员。最有可能的是,您的代码破坏了结构的最后三个字段之一,并且该错误导致了您所看到的错误。将指针移动到最后可能会导致错误停止,但它不能解决问题(您仍在破坏内存,可能会产生许多意想不到的效果)。
这仅仅是基于我在过去所做的那样愚蠢的事情的猜测。没有更多的代码,就无法确定。
我们需要调用代码! – James 2011-06-07 23:41:13
@James我完全删除了调用代码,它仍然崩溃。简单地注释掉Mesh * meshprt;导致它再次正常工作。 – 2011-06-07 23:44:52
@Satchmo布朗 - 给出消息 - '“表达式:无效空指针”,检查'meshptr'是否指向任何有效的位置使用调试器在崩溃的指针。你也违反了**三C++规则**。 – Mahesh 2011-06-07 23:46:57