简体   繁体   English

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

[英]How to free a struct that is inside an other struct

I have the following two structs: 我有以下两种结构:

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;
    }
}

I just used an example of filling some of the variables in them so that I can make my question. 我只是用一个例子来填充其中的一些变量,以便我可以提出我的问题。 What I am facing problem with is how to free the struct "Path" that is contained into the the first struct called name "Label". 我面临的问题是如何释放包含在名为“Label”的第一个结构中的结构“Path”。

I would me sth more than greatful if somenone could give me the code of how to correctly free both structs in C. 如果有人能给我如何在C中正确释放两个结构的代码,我会非常高兴。

In general, you just need to be symmetrical with the calls to malloc / calloc : 通常,您只需要对malloc / calloc的调用进行对称:

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

...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM