【问题标题】:How to free a struct that is inside an other struct如何释放另一个结构内的结构
【发布时间】:2012-06-17 10:17:11
【问题描述】:

我有以下两个结构:

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 中正确释放两个结构的代码,我会非常感激。

【问题讨论】:

  • 这看起来像一个双向链表。我尝试了SO搜索“免费链表”,发现了很多类似的问题。

标签: c struct malloc free


【解决方案1】:

一般来说,你只需要与malloc/calloc的调用对称:

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

...

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

【讨论】:

    猜你喜欢
    • 2021-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    • 2010-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多