How can I have two different structs that refer to each other? One holds a pointer to the other and I also have a forward declaration:
struct json_array_t;
struct json_array_entry_t {
enum json_type type;
union {
bool boolean;
long long integer;
double floating;
char* string;
struct json_array_t array;
};
};
struct json_array_t {
struct json_array_entry_t* entries;
size_t len, cap;
};
I am getting these errors:
error: field ‘array’ has incomplete type
27 | struct json_array_t array;
You must first define struct json_array_t
and then struct json_array_entry_t
.
When you now define in struct json_array_entry_t
an occurrence of json_array_t
it and all its members are fully known to the compiler.
You can define json_array_entry_t
before json_array_t
since you will just use it as a pointer inside json_array_t
#include <stdio.h>
#include <stdbool.h>
// just an example
enum json_type {
_BOOL, _INT, _DOUBLE, _STRING, _ARRAY
};
struct json_array_entry_t;
struct json_array_t {
struct json_array_entry_t* entries;
size_t len, cap;
};
struct json_array_entry_t {
enum json_type type;
union {
bool boolean;
long long integer;
double floating;
char* string;
struct json_array_t array;
};
};
int main() {
// some coding
return 0;
}
The compiler needs to know the exact size of struct json_array_t
to determine how much memory it needs to allocate for the union
member inside of the structure json_array_entry_t
and with that how much memory it needs to allocate for an object of the structure json_array_entry_t
in whole.
A simple forward declaration of struct json_array_t
, as you did, is not sufficient in this case.
Place the definition of struct json_array_t
struct json_array_t {
struct json_array_entry_t* entries;
size_t len, cap;
};
before the definition of struct json_array_entry_t
. In this way the compiler knows the size of the structure json_array_t
and you can also spare the forward declaration of it.
Since entries
is only a pointer you don't need a forward-declaration for json_array_entry_t
.
struct json_array_t {
struct json_array_entry_t* entries;
size_t len, cap;
};
struct json_array_entry_t {
enum json_type type;
union {
bool boolean;
long long integer;
double floating;
char* string;
struct json_array_t array;
};
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.