DevNull DevNull - 2 months ago 7
C Question

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

I have a large number of separate types of data (ie: processes, files, threads, functions, etc) that are defined in short, simple

.c
/
.h
files. Once I finished the implementation of the individual pieces and concluded unit/code-coverage testing, I moved on to connecting the pieces together.

The current implementation utilizes pointer-to-parent-
struct
via
(void *)
pointers in the code, ie:

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

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

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


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


There are a few functions where
typeB
and
typeC
need to talk to each other, but they are rare. Also, both of these
struct
s never need to know about
int a
in the
parent
.

I could remove the
parent struct
pointers, and refactor my function prototypes/definitions to simple all accept
(struct typeA *)
as the argument, access the sub-structures, etc, but it seems overkill, as several functions just need to have access to
typeB
/
typeC
structures and their elements.

Is there a de-facto (non-cargo-cult-programming) standard for handling such an organization of structs (similar to the "don't cast
malloc()
" rule I see repeated so often on this site)?

Thank you.

Answer

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 *.

And what's wrong with forward declarations?

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

As of your question: If you don't want/need to store paren as part of structure then you will need either

a) to pass parent address as a parameter, indeed, or

b) to define static variable like struct typeA *current_parent; and put there address of parent structure before calling any method operating with children.

Last solution is not thread safe though and is error prone.

Comments