代码之家  ›  专栏  ›  技术社区  ›  Cloud

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

  •  1
  • Cloud  · 技术社区  · 8 年前

    我有大量不同类型的数据(例如:进程、文件、线程、函数等),这些数据都是用简单明了的语言定义的 .c / .h 文件夹。一旦我完成了各个部分的实现并完成了单元/代码覆盖率测试,我就开始将这些部分连接起来。

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

    struct typeB {
        int B;
        void *parent;
    };
    
    struct typeC {
        int C;
        void *parent;
    };
    
    struct typeA {
        int a;
        struct typeB *pB;
        struct typeC *pC;
    };
    

    我用过 void * 指针,因为有些 结构 是,如果我使用实际的 pointer-to-struct-type 代替 空洞* .

    有一些功能 typeB typeC 需要互相交谈,但很少。此外,这两个 结构 永远不需要知道 int a 在中 parent .

    我可以移除 parent struct 指针,并将我的函数原型/定义重构为simple-all-accept (struct typeA *) 作为参数,访问子结构等,但这似乎有些过分,因为几个函数只需要访问 髁骨折 / C型 结构及其元素。

    是否有一个事实上的(非货物邪教编程)标准来处理这样的结构组织(类似于“不投射” malloc() “我在这个网站上经常看到重复的规则)?

    非常感谢。

    1 回复  |  直到 8 年前
        1
  •  2
  •   c-smile    8 年前

    由于某些结构非常复杂,我使用了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;
    };
    

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

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

    最后一种解决方案不是线程安全的,而且容易出错。