I'm trying to make a "union-find".
Here is my code :
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;
}
The UnionFind is defined by :
typedef struct unionfind{
unsigned int nbElems;
unsigned int nbGroups;
VertexTree **vt;
}*UnionFind;
And here is the definition of the Tree :
typedef struct sTree{
GraphVertex vtx;
struct sTree* parent;
}VertexTree;
I know the segfault is because the tree is not allocated correctly. Can someone please tell me how to allocate memory correctly for the tree of vertices?
Thanks
UnionFind uf= malloc(sizeof(UnionFind));
I think this is your problem line..
UnionFind
is a pointer type so sizeof
will only return the size of a pointer for your machine.
Try:
UnionFind uf= malloc(sizeof(struct unionfind));
This will return the actual size of the structure.
I found the problem!
I had to allocate the "pointer of pointers" (**vt) and then allocate the pointers for each tree in a for loop.
So the final code is :
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; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.