【发布时间】:2012-05-09 08:03:02
【问题描述】:
我有以下几行代码:
struct c_obj_thing *object = NULL;
c_obj_initalizer(object);
// at this point, (object == NULL) is 'true'
printf("Value: %d\n", object->value); // this segfaults
这是 c_obj_initializer 的定义:
int c_obj_initalizer(struct c_obj_thing *objParam) {
objParam = malloc(sizeof(struct c_obj_thing));
objParam->pointerThing = NULL;
objParam->value = 0;
return 0;
}
为什么 c_obj_initalizer 方法中的 malloc 在方法返回时不与作为参数传递的指针保持连接?似乎对初始化程序的调用没有做任何事情。我意识到传递一个实际的 c_obj_thing 而不是作为指针传递意味着初始化器中所做的更改不会返回,但我认为动态内存会在整个程序中持续存在。
【问题讨论】:
标签: c pointers struct scope malloc