Try if ( tmp->tableA.
table
== NULL )
In your code, the initialization
Outer_t outer_instance = {
{NULL},
{
0,
1,
2,
3,
table_defined_somewhere_else,
}
};
is invalid. You are trying to assign NULL
to Outer_t.tableA
which is of non-pointer type Inner_t
. NULL
can only be assigned to pointers.
Most C compilers define NULL
as 0
or ((void*)0)
. Depending on your compiler, this syntax may be allowed but will be expanded to 0
, effectively setting all fields in the first Inner_t
structure to zero. In any case, this code will not do what I think you believe it will.
Your notion of tableA
being undefined or non-existent is wrong. As your structures are currently defined, declaring an object of type Outer_t
will automatically create two Inner_t
objects as structure members (and those Inner_t
structures will automatically create the objects they are composed of, etc). If outer_instance
exists, then outer_instance.tableA
and outer_instance.tableB
are guaranteed to exist. They cannot be "undefined" (they are defined when you defined the Outer_t
data type) or "NULL" (has no meaning except for pointers). A structure which has members defined is never "empty".
Now, it is a valid concern whether or not tableA
or tableB
have been initialized. There is no universally-appropriate way to do this. One method is to fill the entire structure with some pre-defined value when it is declared, and to check for the presence of that value as a sign that the structure has not been initialized. This assumes, however, that there is a value that you should never see as valid data within that structure; many times, such a value does not exist.
If you want to build your code in such a way that the members of Outer_t
may or may not exist, then you should use pointers (such as Inner_t* tableA
) as members of Outer_t
instead of structures. That way, you can NULL the pointer to indicate a non-existent table. However, you would not be able to declare the contents of the inner structs at the same time as the outer struct in the manner which you currently do.
Edit:
Looking at your updated code, it appears that you are getting that particular error because you are trying to assign an object of type Items_t
to a field of type Items_t*
. Use &items_instance
here and your error should go away (provided that items_instance
is defined before outer_instance
, and all elements of items_instance
can be determined at compile time).
In the revised code, you're setting the first field of outer_instance
to NULL, but trying to set the second field to items_instance
directly. Since the field has type Items_t*
but items_instance
has type Items_t
, you're getting a type error.
You want to set the field to the address of items_instance
, so use &items_instance
.