[英]Can't allocate complex 2D array
我正在嘗試“尋找聯盟”。
這是我的代碼:
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;
這是Tree的定義:
typedef struct sTree{
GraphVertex vtx;
struct sTree* parent;
}VertexTree;
我知道段錯誤是因為樹分配不正確。 有人可以告訴我如何為頂點樹正確分配內存嗎?
謝謝
UnionFind uf= malloc(sizeof(UnionFind));
我認為這是您的問題所在。
UnionFind
是指針類型,因此sizeof
將僅返回計算機的指針大小。
嘗試:
UnionFind uf= malloc(sizeof(struct unionfind));
這將返回結構的實際大小。
我發現了問題!
我必須分配“指針指針”(** 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; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.