c - 如何释放另一个结构体内部的结构体

标签 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 中正确释放这两个结构的代码,我会非常高兴。

最佳答案

一般来说,您只需与对 malloc/calloc 的调用保持对称即可:

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

...

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

关于c - 如何释放另一个结构体内部的结构体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11070565/

相关文章:

c - Strcpy 改变 struct int 数组

C函数名还是函数指针?

c - 现在我已经将结构数组设置为全局数组,出现段错误

c - 创建数组 "normally"和使用 malloc 之间的区别

c - 字节交换和在 C 中用 0 剩余空间的填充

c - 如何创建代码以按排序方式将整数插入链表?

c - 如何分配内存并用指向二维数组的指针填充结构

c - 结构体中的结构体数组?

c - 我如何在 CFFI 中包装包含结构指针的结构?

c - Malloc 的段错误