I’m trying to create a data structure in C to represent graph. I found this very useful link:
http://pine.cs.yale.edu/pinewiki/C/Graphs
It seems to me a quite good starting point. But I have some problem understanding the data structure.
struct graph {
int n; /* number of vertices */
int m; /* number of edges */
struct successors {
int d; /* number of successors */
int len; /* number of slots in array */
char is_sorted; /* true if list is already sorted */
int list[1]; /* actual list of successors */
} *alist[1];
};
I can’t understand why the struct successor is declared as it is and not in this way:
struct graph {
int n; /* number of vertices */
int m; /* number of edges */
struct successors {
int d; /* number of successors */
int len; /* number of slots in array */
char is_sorted; /* true if list is already sorted */
int *list; /* actual list of successors */
} *alist;
};
As I can see in the sequent function to create the graph:
Graph
graph_create(int n)
{
Graph g;
int i;
g = malloc(sizeof(struct graph) + sizeof(struct successors *) * (n-1));
assert(g);
g->n = n;
g->m = 0;
for(i = 0; i < n; i++) {
g->alist[i] = malloc(sizeof(struct successors));
assert(g->alist[i]);
g->alist[i]->d = 0;
g->alist[i]->len = 1;
g->alist[i]->is_sorted= 1;
}
return g;
}
It allocates more spaces for alist and I can’t understand why declare it as alist[1].
Can you please explain me how this works?
I hope the question is clear, because I’m quite confused myself.
Uses double indirection (each pointer op
*/&and the subscript operator[]is a level of indirection and requires an additional memory access) on thealistmember to enable each index to bemalloc‘d.Does not.
Also, from your link:
That link has quite a lot of code.
I don’t fully understand how
->listis used but your approach only reserves space forint *while the original reserves both the pointer and the targetint.The allocation of
only allocs
successors *so eachsuccessorsobject can (in theory) be crudely extended to point to moreint‘s.