在C中的函数中将结构指针设置为NULL

时间:2017-01-15 19:07:34

标签: c pointers

我尝试使用函数释放结构指针,然后检查NULL。它不起作用!

typedef struct{
    int * num;
} D;

void freeD(D * a){
    free(a->num);
    free(a);
    a=NULL;
}
int main(){
    D * smth = malloc(sizeof(D));
    smth->num = malloc(sizeof(int)*2);
    freeD(smth);
    if(smth==NULL){
    printf("It's NULL");
    }
}

2 个答案:

答案 0 :(得分:3)

您必须通过使用指向指针的引用传递指针。

例如

[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];

答案 1 :(得分:0)

这里您已经按值传递了参数,而不是通过引用传递参数。

你做了什么
我们假设smth = 0x0030;
其中地址(smth)= 0x0100&& value(smth)= 0x0030
因此,当你执行freeD(smth)时,实际上是在传递 值(smth) ,即0x0030。同时,在函数freeD()中: -
地址(a)= 0x0200&&值(a)= 0x0030
所以当你设置

  

a = NULL

你实际设置值(a)= NULL其中地址(a)= 0x0200;而不是在地址= 0x0100;左

你应该做什么

void freeD(D ** a){
free((*a)->num);
free(*a);
*a=NULL; 
}

int main(){
//...    
freeD(&smth);
//...
}