指针未设置为NULL(C)

时间:2014-09-06 20:15:03

标签: c pointers struct null

我正在试图弄清楚如何在函数中将结构指针设置为NULL。这是我的代码。

struct object
{
    char* name;
    int type;
};

struct object* createObject(char* new_name, int new_type)
{
    struct object* new_object = (struct object*) malloc(sizeof(struct object));

    new_object->name = (char*) malloc(sizeof(char) * (strlen(new_name) + 1));

    strcpy(new_object->name, new_name);
    new_object->type = new_type;

    return new_object;
}

void freeData(struct object* clearedObject)
{
    free(clearedObject->name);
    clearedObject->name = NULL;
    clearedObject->type = 0;
}

void freeObject(struct object* deadObject)
{
    free(deadObject);
    deadObject = NULL;
}

int main(void)
{
    struct object* my_object = createObject("Test", 1234);

    printf("Pointer to Object: %p\n", my_object);
    printf("Pointer to Name  : %p\n", my_object->name);
    printf("Name: %s\n", my_object->name);
    printf("Type: %d\n", my_object->type);
    printf("\n");

    freeData(my_object);

    printf("Pointer to Object: %p\n", my_object);
    printf("Pointer to Name  : %p\n", my_object->name);
    printf("Name: %s\n", my_object->name);
    printf("Type: %d\n", my_object->type);
    printf("\n");

    freeObject(my_object);

    printf("Pointer to Object: %p\n", my_object);
}

这是代码输出的内容:

Pointer to Object:  005E17B8
Pointer to Name  :  005E17D8
Name:  Test
Type:  1234

Pointer to Object:  005E17B8
Pointer to Name  :  00000000
Name:  (null)
Type:  0

Pointer to Object:  005E17B8

为什么我可以在函数中将结构名称的指针设置为NULL,而不是实际的struct指针本身?怎么办呢?
我需要在函数中将my_object设置为NULL,这怎么可能? 感谢。

1 个答案:

答案 0 :(得分:3)

按以下方式定义功能

void freeObject(struct object ** deadObject)
{
    free( *deadObject);
    *deadObject = NULL;
}

并称之为

freeObject( &my_object );

原始函数的问题是参数是函数的局部变量。局部变量的任何更改都不会影响原始参数。