0

Given these two structs:

typedef struct graph {
    int number_vertices;
    vertex *vertices;
} graph;

typedef struct vertex {
    int id;
    linked_list *out_neighbours;
    linked_list *in_neighbours;
} vertex;

How is it possible to add multiple vertices to a graph?

2 Answers 2

2

Like this:

graph g;
g.number_vertices = n;
g.vertices = malloc(n * sizeof(vertex)); // allocate dynamic memory for `n` vertices
                                         // and make g.vertices point to that memory
// fill g.vertices[0], g.vertices[1], …, g.vertices[n-1]

// …

// deallocate the memory when you're done:
free(g.vertices);
Sign up to request clarification or add additional context in comments.

Comments

0

Allocate a buffer large enough to store the vertices, and store the pointer to it in the variable vertices in the struct graph.

struct graph g;
g.number_vertices = 10;  // If you want to store 10 vertices
g.vertices = (vertex*)malloc(g.number_vertices * sizeof(struct vertex));
g.vertices[0]... // To access the first.
g.vertices[1]... // To access the second.
g.vertices[2]... // To access the third, etc.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.