C - Graph Node (undirected) that can add neighbors

Viewed 74

I'm trying to write a simple undirected graph node with the following requirements:

-can stores any type of data

-stores pointers to all neighbors

-within the graph node struct have a function that can add/remove neighbours. Such that I can simply call: node.add_neighbor(other_node);

I currently have the following:

struct GraphNode{
    int number_of_connected_nodes;
    struct TreeNode** neighbors; //dynamically resize as neighbors are added/removed
    void *data;
    void(*add_neighbor)(struct GraphNode * self,other) 
//how do I ensure that "this" object is always passed to self in the function pointer?
}


static void connect_node(struct GraphNode * self,other){
    self->number_of_connected_nodes=self->number_of_connected_nodes+1;
    self->connected_nodes=realloc(self->connected_nodes,self->number_of_connected_nodes * sizeof(struct GraphNode*));
    self->connected_nodes[(self->number_of_connected_nodes -1)] =other;
}

struct GraphNode* create_graph_node() {
    struct GraphNode *graph_node = malloc(1 * sizeof(struct GraphNode));
    graph_node->number_of_connected_nodes = 0;
    graph_node->neighbors = NULL;
    graph_node->add_neighbor=connect_node;
}

The main issue I am having is that if i use a function pointer I dont know how to add a neighbor to the object itself as part of the struct.

Any other thoughts or comments how I can make this better is greatly appreciated as well.

1 Answers

The most common convention is:

#define AddNode(from, to)  (from)->add_neighbour((from), (to))

If you are worried about some client of your library messing with you, don’t. They can always find a way to subvert your guards nomatter what the language.

If you want a tidier syntax, Go would be a good choice. It maintained the pleasant bits of C, without devolving into the morass that other C derivatives have.

Related