首页 > 解决方案 > 如何释放结构中的字符数组

问题描述

我看到您可以在 struct 中释放 char * 指针,但是如何在 struct 中释放 char[N]

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

当我这样做时,我得到一个错误

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

标签: c

解决方案


如果char number[13]在 struct 中使用 char 数组 ( ),则不必malloc使用free数组。一旦你malloc为 struct Edge 做了,内存中也有数字空间。

总之,如果您使用 char 指针作为 的成员struct Edge,则需要char 指针mallocfree内存空间,但在您的情况下您不必这样做。因此,删除free(edge->number)行。


推荐阅读