两个相互引用的结构 [英] two structs that refer to each other

查看:55
本文介绍了两个相互引用的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何让两个不同的结构体相互引用?一个持有指向另一个的指针,我也有一个前向声明:

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;
};

我收到这些错误:

error: field ‘array’ has incomplete type
   27 |         struct json_array_t array;

推荐答案

编译器需要知道 struct json_array_t 的确切大小,以确定它需要为 union 分配多少内存 结构 json_array_entry_t 内部的成员,以及它需要为结构 json_array_entry_t 的整个对象分配多少内存.

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.

在这种情况下,像您一样对 struct json_array_t 进行简单的前向声明是不够的.

A simple forward declaration of struct json_array_t, as you did, is not sufficient in this case.

放置struct json_array_t

struct json_array_t {
    struct json_array_entry_t* entries; 
    size_t len, cap;
};

struct json_array_entry_t的定义之前.这样编译器就知道结构json_array_t的大小,你也可以省去它的前向声明.

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.

由于 entries 只是一个指针,您不需要 json_array_entry_t 的前向声明.

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; 
    }; 
}; 

这篇关于两个相互引用的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆