Can';不分配复杂的二维数组

Can';不分配复杂的二维数组,c,C,我想找一个“联盟” 这是我的密码: 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++){

我想找一个“联盟”

这是我的密码:

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;
}
下面是树的定义:

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=顶点_MAX;
uf->nbGroups=顶点_最大值;
uf->vt=malloc(顶点_MAX*sizeof(VertexTree*);//uf->vt现在已定义
int i;
对于(i=0;元素内;i++){
uf->vt[i]=malloc(sizeof(VertexTree));//我现在可以逐个分配树了
uf->vt[i]->vtx=i+1;
uf->vt[i]->parent=uf->vt[i];
}
返回uf;

}

访问
uf->vt[i]->vtx
会导致未定义的行为。你应该在
uf->nbGroups=…
之后写一个for循环初始化每个vt[i]。
for(i=0;i<11;+i){uf->vt[i]=malloc(sizeof**uf->vt->vt);}
给你segfault?是的,但是为什么
**uf->vt
?Siges只适用于数据类型,对吗?我尝试过“代码> Malc(sisiof of *uf-> vt)< /c>”,它也给了我一个Sebug。@ Elirovi,如果这回答了你的问题,即使你发现了问题,也可以接受它作为答案。这可能是一个更详细的答案,但它仍然是一个答案。我只是尝试了
struct unionfind
它不起作用。很奇怪,当你试着这么做的时候,你从哪里得到了segfault?@bhzag在同一行(
uf->vt[i]=malloc(sizeof(VertexTree));
)@bhzag刚刚意识到他的for循环是从
0迭代到VERTEX_MAX
,看起来比11大得多。还记得我告诉你的
sizeof
<代码>UnionFind uf=malloc(sizeof(UnionFind))视为
struct unionfind*uf=malloc(sizeof(struct unionfind*)),这是错误的。您正在为
struct unionfind
指针分配空间,而实际需要为
struct unionfind
分配空间。将其更改为
UnionFind uf=malloc(sizeof*uf)uf->vt=malloc(11*sizeof(VertexTree*))分配了“指针指针指针”。我认为
11==VERTEX\u MAX
,否则for循环访问的索引超出了范围。
typedef struct sTree{
    GraphVertex vtx;
    struct sTree* parent;
}VertexTree;