简体   繁体   English

如何在结构中释放字符数组

[英]How to free char array in struct

I see that you can free char * pointers within struct but how do you free char[N] inside a struct我看到你可以在结构中释放 char * 指针,但是你如何在结构中释放 char[N]

typedef struct Edge
{
    char number[13];
    int numOfCalls;
    struct Edge *next;
} Edge;

When I do this i get an error当我这样做时,我收到一个错误

Edge *edge = malloc(sizeof(Edge));
edge->next = NULL;
strcpy(edge->number,numberOne);  // numberOne is also a char[13];
free(edge->number);
free(edge);

If you use char array ( char number[13] ) in struct, you don't have to malloc or free the array.如果在结构中使用 char 数组( char number[13] ),则不必mallocfree该数组。 Once you do malloc for struct Edge, there is also space for number in memory.一旦你对 struct Edge 执行malloc ,内存中也有数字空间。

In summary, if you use char pointer as a member of struct Edge , you need to malloc or free memory space for char pointer, but you don't have to do that in your case.总之,如果您使用 char 指针作为struct Edge的成员,则需要为 char 指针分配mallocfree内存空间,但在您的情况下不必这样做。 Therefore, delete free(edge->number) line.因此,删除free(edge->number)行。

The lifespan of number in the struct Edge is automatic.结构Edgenumber的生命周期是自动的。 Even if you dynamically allocate an Edge struct, when you free the struct, you'll free the memory for the char array.即使您动态分配Edge结构,当您free该结构时,您也会为 char 数组释放内存。

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

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