如何释放其他结构中的结构

时间:2012-06-17 10:17:12

标签: c struct malloc free

我有以下两种结构:

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”的第一个结构中的结构“Path”。

如果有人能给我一些如何在C中正确释放两个结构的代码,我会非常感激。

1 个答案:

答案 0 :(得分:2)

一般情况下,您只需要与malloc / calloc的调用保持对称:

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

...

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