我试图做一个“联合发现”。无法分配复杂的2D阵列
这里是我的代码:
UnionFind uf_create(){
UnionFind uf= malloc(sizeof(UnionFind));
uf->vt=malloc(11*sizeof(VertexTree*));
uf->nbElems=VERTEX_MAX;
uf->nbGroups=VERTEX_MAX;
int i;
for(i=0;i<uf->nbElems;i++){
printf("%d\n", i);
uf->vt[i]->vtx=i+1;
uf->vt[i]->parent=uf->vt[i];
}
return uf;
}
的UnionFind被定义为:
typedef struct unionfind{
unsigned int nbElems;
unsigned int nbGroups;
VertexTree **vt;
}*UnionFind;
这里是树的定义:
typedef struct sTree{
GraphVertex vtx;
struct sTree* parent;
}VertexTree;
我知道段错误是因为树没有正确分配。 有人可以告诉我如何正确地为顶点树分配内存吗?
感谢
访问'UF-> VT [I] - > vtx'导致未定义的行为。你应该在'uf-> nbGroups = ...'之后立即写一个for循环来初始化每个vt [i]。 – ddz
这就是我刚刚做的,现在段错误发生在分配线(“uf-> vt [i] = malloc(sizeof(VertexTree));”) – Elirovi
(i = 0; i <11; + + i){uf-> vt [i] = malloc(sizeof ** uf-> vt); }'给你段错误? – ddz