2010-11-30 117 views
1
//CHILD 
typedef struct Child{ 
    int id; 
}Child; 
Child* newChild(){ 
    Child *aChild = malloc(sizeof(Child)); 
    aChild->id = 0; 
    return aChild; 
} 

//PARENT 
typedef struct Parent{ 
    int id; 
    Child **children; 
}Parent; 

Parent* newParent(){ 
    Parent *aParent = malloc(sizeof(Parent)); 
    aParent->id = 0; 
    aParent->children = malloc(sizeof(Child*) * 5);//ARRAY OF 5 CHILDREN? 
    for(i=0; i<5; i++){ 
     aParent->children[i] = newChild(); 
    } 
    return aParent; 
} 

是否newParent()函数是用数组children创建结构的正确方法?我主要关注的是行:c结构关系

aParent->children = malloc(sizeof(Child*) * 5); 

回答

2

您应该检查是否malloc居然成功了,但除此之外,代码确定。

0

正如Let_Me_Be所说,原则上没有错误的代码。不过,我想,如果我可以说你可能想要做这样指出:

Parent *p = newParent(); 

但是不是很明显的是,大量的内存刚被分配。如果你没有跟踪它,或忘记释放它,你有一个问题。另外,如果您希望调整其大小,则不知道有多少个孩子。我可能会建议:

typedef struct Parent{ 
    int id; 
    int numchildren; 
    Child **children; 
}Parent; 

,我可能会提出类似的功能:

int parent_array_Initialise(Parent *p, int num_children) 
{ 
    p = malloc(sizeof(Parent)); 
    ... 
} 

int parent_array_children_resize(Parent *p, int new_children_size); 

int parent_array_Free(Parent *p); 

然后调用函数。这个想法是在每种情况下返回malloc的结果(大小为 数组,如果成功,则返回0),以便可以测试malloc结果。

只是我个人的品味。无论你做什么,只要通过valgrind或类似的方法传递结果就可以确保你没有泄漏记忆。