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

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

4

1 回答 1

2

通常,您只需要对malloc/的调用保持对称即可calloc

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

...

free(current->head);
free(current);
于 2012-06-17T11:04:21.043 回答