C NULL与空结构相同

C NULL与空结构相同,c,struct,null,C,Struct,Null,假设我有一个基本结构,只有几个值: struct my_struct { int val1; int val2; } 我想把它传递给一个函数 int test_the_struct(struct my_struct *s); 然后在该函数中,我检查NULL并返回一个错误代码,但如果传递的是空结构,我希望它继续。例如: struct my_struct *test_struct = (struct test_struct *) calloc(1, sizeof(struct t

假设我有一个基本结构,只有几个值:

struct my_struct {
    int val1;
    int val2;
}
我想把它传递给一个函数

int test_the_struct(struct my_struct *s);
然后在该函数中,我检查NULL并返回一个错误代码,但如果传递的是空结构,我希望它继续。例如:

struct my_struct *test_struct = (struct test_struct *) calloc(1, sizeof(struct test_struct));
test_the_struct(NULL); //this should fail
test_the_struct(test_struct); //this should not fail

我如何区分这两者?在这种情况下,我无法更改
my_struct

的结构。如果我理解正确,您就不会有问题

只需对照
NULL
检查指针即可

int test_the_struct(struct my_struct *s)
{
    if (s) { // or if (s != NULL) or whatever you want to express it...
        return s->val1 + s->val2;
    } else {
        return 42;
    }
}

如果使用
测试结构调用它,则两个值都是
0
。它没有任何错误或特殊之处。

要查找指针
s
是否为空,可以使用

if (s) {
    /* not null */
} else {
    /* is null */
}

指向“空”结构的指针不为空。

按以下方式设计函数

int test_the_struct(void *ptr)
{
if (ptr == NULL)
     return -1; //error
else 
     return 0;
}

检查指针是否为空…就像您可以检查
if(s==NULL)…
并且不强制转换
calloc
malloc
的返回值一样。。。很可能是在你的代码中隐藏了错误…显然我没有。我的代码在其他地方失败了,我只是有一个隧道式的视野。谢谢应该使用struct my_struct*ptr,但如果您传递任何其他指针,编译器将发出警告..因此,为了避免这种情况,只需使用void*pointer...@Mr.32:但您不知道OP在函数中做什么。如果他试图去引用它呢?取消对空指针的引用有点不正确