Returning NULL if structure initialization failed in C?
c, initialization, struct
Solution
if( mystruct == NULL )
`mystruct` is not a pointer, so you cannot compare it with `NULL`.
You have three options:
- Add a status field to `MyStruct` to indicate whether the struct has been initialized correctly.
- Allocate the struct on the heap and return it by pointer.
- Pass the structure as a pointer argument and return a status code (thanks @Potatoswatter).
Problem
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)?