我有这个 C 代码:
#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;
}
它有一个结构和一个初始化该结构的函数。如果该函数出现故障,我要做的是返回 NULL 。
gcc 错误信息:
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
看起来返回NULL而不是结构是无效的,那么在这种情况下如何表达结构初始化失败(没有结构指针)?