结构指针在C
问题描述:
另一个结构鉴于这两种结构:结构指针在C
typedef struct graph {
int number_vertices;
vertex *vertices;
} graph;
typedef struct vertex {
int id;
linked_list *out_neighbours;
linked_list *in_neighbours;
} vertex;
怎么可能到多个vertices
添加到?
答
像这样:
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);
答
分配大到足以存储顶点缓冲区,指针将其存储在变量vertices
在结构。
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.
[您不应该投射malloc的结果](http://*.com/q/605845/3425536)。 – emlai