2012-06-17 119 views
0

裏面我有以下兩種結構:如何釋放一個結構是一個其他結構

typedef struct label{ 

    int id; 
    double p,*t,q,c; 

    int V[45]; 
    struct label *next; 
    struct label *prev; 
    struct path *tail; 
    struct path *head; 

}label; 

typedef struct path{ 
    int i; 

    struct path *Pperv; 
    struct path *Pnext; 
}path; 

void main(){ 

    int i,j; 
    struct label *Current,*Head,*Tail; 
    struct path *test1,*path_head,*path_tail; 

    Head=(struct label*)malloc(1*sizeof(struct label)); 
    Tail=(struct label*)malloc(1*sizeof(struct label)); 

    Head->next=Tail; 
    Tail->prev=Head; 


    for (i=0;i<250000;i++) 
    { 
     Current=(struct label*)malloc(1*sizeof(struct label)); 
     Current->t=(double*)malloc(15*sizeof(double)); 

     Current->head=(struct path*)malloc(1*sizeof(struct path)); 
     Current->tail=(struct path*)malloc(1*sizeof(struct path)); 
     Current->head->Pnext=Current->tail; 
     Current->tail->Pperv=Current->head; 

     for (j=0;j<15;j++) 
     { 
      test1=(struct path*)malloc(1*sizeof(struct path)); 

      test1->Pperv=Current->head; 
      test1->Pnext=Current->head->Pnext; 

      Current->head->Pnext->Pperv=test1; 
      Current->head->Pnext=test1; 


      test1->i=1; 
      Current->t[j]=23123.4323334; 

     } 
     Current->next=Tail; 
     Current->prev=Tail->prev; 
     Tail->prev->next=Current; 
     Tail->prev=Current; 
     Current->p=54545.323241321; 
    } 
} 

我只是用一些填充在其中的變量,這樣我可以讓我的問題的一個例子。我面臨的問題是如何釋放名爲「Label」的第一個結構中包含的struct「Path」。

我想我比折騰更感激如果somenone可以給我在C

+0

這看起來像一個雙向鏈表。我嘗試了搜索「免費鏈接列表」,並發現了很多與此類似的問題。 –

回答

2

一般如何正確地解放了結構的代碼,你只需要與調用是對稱malloc/calloc

label *current = malloc(sizeof(*current)); 
current->head = malloc(sizeof(*current->head)); 

... 

free(current->head); 
free(current);