[英]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]
),则不必malloc
或free
该数组。 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 指针分配malloc
或free
内存空间,但在您的情况下不必这样做。 Therefore, delete free(edge->number)
line.因此,删除
free(edge->number)
行。
The lifespan of number
in the struct Edge
is automatic.结构
Edge
中number
的生命周期是自动的。 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.