I have this C code :
#include<stdio.h>
typedef struct {
int foo;
} MyStruct;
MyStruct init_mystruct(void);
int main(void) {
MyStruct mystruct = init_mystruct();
if( mystruct == NULL ) {
/* error handler */
}
return(0);
}
MyStruct init_mystruct(void) {
MyStruct mystruct;
int is_ok = 1;
/*
* do something ...
*/
/* everything is OK */
if( is_ok )
return mystruct;
/* something went wrong */
else
return NULL;
}
It has a structure and a function to initialize that structure. What I’m trying to do is to return NULL if there was a failure in that function.
The gcc error message :
code.c: In function ‘main’:
code.c:13: error: invalid operands to binary == (have ‘MyStruct’ and ‘void *’)
code.c: In function ‘init_mystruct’:
code.c:34: error: incompatible types when returning type ‘void *’ but ‘MyStruct’ was expected
It looks that returning NULL instead of a structure is not valid, so how do I express the failure of structures initialization in this case (no structure pointer)?
mystructis not a pointer, so you cannot compare it withNULL.You have three options:
MyStructto indicate whether the struct has been initialized correctly.