在C函数中将结构指针设置为NULL [英] Set structure pointer to NULL in function in C

查看:154
本文介绍了在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 );

这篇关于在C函数中将结构指针设置为NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆