gpt4 book ai didi

c - 释放包含双指针的结构

转载 作者:太空宇宙 更新时间:2023-11-04 02:27:47 24 4
gpt4 key购买 nike

假设我有一个定义如下的结构:

typedef struct {
int width;
int height;
char **data;
} puzzle;

然后,根据我的教科书,free 函数应该是这样的:

void puzzle_free(puzzle** puzzle) 

但我不明白为什么 puzzle 应该是 free 函数中的双指针。

最佳答案

它可能与结构中包含的双指针无关,而只是一种编写自由函数的方式,有助于防止释放后访问。
尤金·史在他的评论中提到它。

puzzle_free 的实现是:

void puzzle_free(puzzle** puzzle_p) {
puzzle *puzzle = *puzzle_p
// Somehow free puzzle->data
free(puzzle);
*puzzle_p = NULL;
}

用法是:

puzzle *puzzle = malloc(...)
// Fill it, use it.
puzzle_free(&puzzle);
// puzzle pointer is now NULL

关于c - 释放包含双指针的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48548469/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com