Deep copy of graph structure

I have a graph structure in C and you want to make a deep copy of it (including nodes and edges).

The structure is as follows:

struct li_list {
    struct li_node n;
};

struct li_node {
    struct li_node *next, *prev;
};

struct gr_graph {
    struct li_list nodes;
    int nodecount;
};

struct gr_node {
    struct li_node node;
    struct gr_graph *graph;
    int pred_count, succ_count;
    struct li_list pred, succ;
};

struct gr_edge {
    struct li_node succ, pred;
    struct gr_node *from, *to;
    unsigned long marks;
};

These structures do not exist as they are, but are “inherited” in another structure, for example:

struct ex_node {
    struct gr_node _; // "Superclass"
    int id;
    struct ex_node *union_find_parent;
    ...
}

Is there an elegant solution to create such a deep copy of such a structure, including updating links to copies?

Note. Members of nested structures do not indicate the root structure that it contains, but their associated nested structure (for example, ex_node._.pred.n.nextpoints to ex_edge._.pred). This implies tedious pointer arithmetic when they need to be updated.

My decision is still

  • Memcopy all structs
  • Iterate over all copies
  • , (- RTTI C , , )
    • offsetof
    • offsetof,

? , -, .

+5
4

, , , , , , - ( ) malloc ex_node. ...

, , , .

+1

. $0,02:

  • , li_list li_node. , li_node?
  • (, ) ++ ( , )
  • memcpy . .
  • , :

:

struct foo {
   int datum;
   int *p;
   foo_copy pfoo;
};

typedef void (*foo_copy)(const struct foo *src, struct foo *dst);

void foo_cp(const struct foo *src, struct foo *dst)
{ 
    *dst = *src; // copy non-pointer data
    dst->p = malloc(sizeof *dst->p);
    dst->p = *src->p;
}


// somewhere else
struct foo s;
// initalize
struct foo *t = malloc(sizeof *t);  
s.copy(&s, &t);

...

+1

memcpy all structs , .

. .

+1

, , .

-, . DFS (Depth First Search) BFS (Breadth First Search) . , node .

- ( )   ,  , .

. ,  , ,   .  (, node5 1 , 7 node 11,       graph2 5 7 11.)

0
source

All Articles