【问题标题】:Struct pointer to another struct in CC中指向另一个结构的结构指针
【发布时间】:2017-07-13 01:32:49
【问题描述】:

鉴于这两个结构:

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?

【问题讨论】:

    标签: c data-structures struct


    【解决方案1】:

    像这样:

    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);
    

    【讨论】:

      【解决方案2】:

      分配一个足够大的缓冲区来存储顶点,并将指向它的指针存储在结构体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.
      
      猜你喜欢
      • 1970-01-01
      • 2018-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 2021-07-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多