我已经很长时间没有使用 C 语言了,对它还是有些陌生。我对指针和引用的语法感到困惑。基本上我有一个带有指针的结构容器,我动态分配为数组。我想知道如何在完成后释放该内存。这是它的样子:
typedef struct {
int* foo;
} Bar;
typedef Bar * BarRef;
BarRef newBar(int n) {
BarRef B = malloc(sizeof(Bar));
B->foo = calloc(n,sizeof(int));
}
/* This is what I am having trouble understanding */
void freeBar(BarRef *B) {
free(B->foo);
B->foo = NULL;
free(B);
*B = NULL;
}
我收到一个编译器错误,告诉我我正在请求一个不是结构的成员。但我认为传递 Ref*
会取消引用,所以这就像传递结构一样。我正在使用 gcc 和 ANSI C。
最佳答案
void freeBar(BarRef * B) {
// Here B is a pointer to a pointer to a struct Bar.
// Since BarRef is Bar *
// And B is a BarRef *
}
由于您要修改指向 struct Bar 的指针(将指针设置为 NULL),因此传入 BarRef * 是正确的,但是您的过程的内容应该如下所示:
free((*B)->foo);
(*B)->foo = NULL;
free(*B);
*B = NULL;
(*B)->foo
的工作方式如下:
(*B)
取消引用 B,给你一个 BarRef
(又名 Bar *
)
(*B)->foo
访问 (*B)
foo
的元素
B->foo
无效。即访问B
指向的bar结构中名为foo
的元素。因为 B
没有指向 bar 结构,而是指向一个 pointer to a bar structure
你得到“从不是结构的东西请求成员”错误。 “不是结构的东西”是指向结构的指针。
关于c - 如何从结构内部释放动态分配的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8109180/