簡體   English   中英

指向C中另一個結構的結構指針

[英]Struct pointer to another struct in C

鑒於以下兩個結構:

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

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

如何在一個graph上添加多個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);

分配足夠大的緩沖區以存儲頂點,並將指向它的指針存儲在struct graph的可變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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM