2010-11-30 100 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或類似的方法傳遞結果就可以確保你沒有泄漏記憶。