문제

So say I have a basic struct with just a couple of values:

struct my_struct {
    int val1;
    int val2;
}

and I want to pass it to a function

int test_the_struct(struct my_struct *s);

and then inside that function I check for NULL and returns an error code, but I want it to continue if an empty struct is passed instead. For example:

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

How could I differentiate between the two? In this situation, I CANNOT alter the structure of my_struct

도움이 되었습니까?

해결책

If I understand you correctly, you just don't have a problem.

Just check the pointer against NULL and you are fine.

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;
    }
}

If you call it with your test_struct, both values are 0. There is nothing wrong or special about it.

다른 팁

To find if a pointer s is null you can use

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

A pointer to an "empty" struct is not null.

design your function as belows

int test_the_struct(void *ptr)
{
if (ptr == NULL)
     return -1; //error
else 
     return 0;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top