带有指向父结构指针的结构:最佳方法

struct with pointer-to-parent-struct: best approach

我有大量不同类型的数据(即:进程、文件、线程、函数等),它们定义在简短的 .c/.h 文件中。一旦我完成了各个部分的实施并结束了 unit/code-coverage 测试,我就开始将各个部分连接在一起。

当前的实现通过代码中的 (void *) 指针使用指向父对象的指针-struct,即:

struct typeB {
    int B;
    void *parent;
};

struct typeC {
    int C;
    void *parent;
};

struct typeA {
    int a;
    struct typeB *pB;
    struct typeC *pC;
};

由于某些 struct 非常复杂,我使用了 void * 指针,如果我使用实际的 pointer-to-struct-type 代替 [,它们将无法编译=15=].

有一些函数 typeBtypeC 需要相互通信,但这种情况很少见。此外,这两个 struct 永远不需要知道 parent 中的 int a

我可以删除 parent struct 指针,并重构我的函数 prototypes/definitions 以简单地接受 (struct typeA *) 作为参数,访问子结构等,但这似乎有点过分了,因为几个函数只需要访问 typeB/typeC 结构及其元素。

是否有处理这种结构组织的实际(非货物崇拜编程)标准(类似于我在本网站上经常看到的 "don't cast malloc()" 规则)?

谢谢。

I used void * pointers due to how complicated some structs are, and they won't compile if I use actual pointer-to-struct-type in place of void *.

前向声明有什么问题?

struct typeA; // forward declaration

struct typeB {
    int B;
    struct typeA *parent;
};

struct typeC {
    int C;
    struct typeA *parent;
};

struct typeA {
    int a;
    struct typeB *pB;
    struct typeC *pC;
};

关于你的问题:如果你不 want/need 将 paren 存储为结构的一部分,那么你将需要

a) 确实将父地址作为参数传递,或者

b) 定义像 struct typeA *current_parent; 这样的静态变量,并在调用任何操作子对象的方法之前将父结构的地址放在那里。

尽管最后一个解决方案不是线程安全的并且容易出错。