在C函数中将结构指针设置为NULL
问题描述:
我尝试使用函数释放结构指针,然后检查NULL.它不起作用!
I try to free structure pointer using function and then check for NULL. It doesn't work!
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");
}
}
答
您必须通过引用传递指针,即通过使用指向指针的指针.
You have to pass the pointer by reference that is by using pointer to the pointer.
例如
void freeD(D ** a){
free( ( *a )->num);
free(*a);
*a=NULL;
}
//...
freeD( &smth );