无法分配复杂的2D阵列

时间:2016-04-29 02:42:19

标签: c

我试图制作" union-find"。

这是我的代码:

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;

我知道segfault是因为树没有正确分配。 有人可以告诉我如何为顶点树正确分配内存吗?

由于

2 个答案:

答案 0 :(得分:0)

UnionFind uf= malloc(sizeof(UnionFind));

我认为这是你的问题。

UnionFind是指针类型,因此sizeof只会返回机器指针的大小。

尝试:

UnionFind uf= malloc(sizeof(struct unionfind));

这将返回结构的实际大小。

答案 1 :(得分:0)

我发现了问题!

我必须分配“指针指针”(** vt),然后在for循环中为每个树分配指针。

所以最终的代码是:

UnionFind uf_create(){ UnionFind uf= malloc(sizeof(UnionFind)); uf->nbElems=VERTEX_MAX; uf->nbGroups=VERTEX_MAX; uf->vt=malloc(VERTEX_MAX*sizeof(VertexTree*));//uf->vt is now defined int i; for(i=0;i<uf->nbElems;i++){ uf->vt[i]=malloc(sizeof(VertexTree));//I can now allocate the trees one by one uf->vt[i]->vtx=i+1; uf->vt[i]->parent=uf->vt[i]; } return uf; }

相关问题