将指针设置为``null''内部函数内部的指针
我是C编程语言的新手,我正在尝试制作一种创建结构的惯用模式(例如,一系列标准的构造函数,破坏者等)这样
typedef struct _OBJECT
{
char *data;
} object_t;
object_t *object_new(char *data)
{
object_t *ret = malloc(sizeof(*ret));
if (ret != NULL)
ret->data = data;
return ret;
}
void object_delete(object_t *obj)
{
if (obj != NULL)
{
free(obj);
obj = NULL;
}
}
:但是,由于我无法在释放它后将函数的参数设置为null
,因此 - 式功能。我相当确定这与可可对象中堆栈中声明的数据是不可能的。是否有一种方法可以使此声明持续持续,或者将指针设置为null
在功能之外的最佳处理方式?
I'm fairly new to the C programming language, and I am trying to make an idiomatic pattern for creating structures (i.e. a series of standard constructors, destructors, etc.) like so:
typedef struct _OBJECT
{
char *data;
} object_t;
object_t *object_new(char *data)
{
object_t *ret = malloc(sizeof(*ret));
if (ret != NULL)
ret->data = data;
return ret;
}
void object_delete(object_t *obj)
{
if (obj != NULL)
{
free(obj);
obj = NULL;
}
}
I seem to be having an issue with making a destructor-esque function, though, as I am unable to set the argument of the function to NULL
after freeing it. I am fairly sure this has to do with the fact that data declared on the stack in a callable object is impersistent. Is there a way to make this declaration persistent or is setting the pointer to NULL
outside the function the best way of handling things?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果要将参数设置为
NULL
,请将函数的参数类型更改为 double指针并将对象的地址传递给函数。取消引用函数参数将为您提供对象,其地址作为参数传递,然后您可以在释放内存后将其设置为NULL
。也就是说,以下是您需要在object_delete()
函数中进行的更改:像这样调用
object_delete()
函数:If you want to set the argument to
NULL
, change the parameter type of function to double pointer and pass the address of object to the function. Dereferencing the function parameter will give you the object, whose address passed as argument, which then you can set toNULL
after deallocating memory. That said, below are the changes you need to do inobject_delete()
function:Call
object_delete()
function like this:如果要修改指针的值,则需要将指针传递给指针:
请注意,对指针进行空测试没有多大意义,因为
free
确实如此无论如何。If you want to modify the pointer's value, then you need to pass a pointer to the pointer:
Note that there's not much point in null-testing the pointer, because
free
does that anyway.指针就是值,而 C 是一种按值传递语言。
换句话说,
object_t *obj
是传递给object_delete
的指针的本地副本。一个选择是另一级间接。
Pointers are values, and C is a pass-by-value language.
In other words,
object_t *obj
is a local copy of the pointer passed toobject_delete
.One option is another level of indirection.