【问题标题】:Allocate memory struct of a struct matrix分配结构矩阵的内存结构
【发布时间】:2016-04-29 20:05:07
【问题描述】:

我的结构是:

typedef struct grafo GRAFO;
struct aresta {

    int adj; 
    float peso;
};

struct grafo {
    struct aresta **arestas;
};

我无法像这样对矩阵 arestas 进行 malloc:

GRAFO *grafo_aux = (GRAFO*) malloc(sizeof(GRAFO));
grafo_aux->arestas = malloc(num_vert * sizeof(struct aresta*));

什么是正确的代码?谢谢!

【问题讨论】:

  • 为什么arestas 中的grafo 是双指针?我认为没有必要
  • 你怎么知道不对?见minimal reproducible example
  • @BarthyB。 - 你为什么这么说?我们不知道 OP 的问题/解决方案。
  • @BarthyB。在malloc 中使用num_vert 表示arestas 意味着它可能是一个列表。
  • @Ben 标题说矩阵在我看来更像是一个数组而不是一个列表。为此,您不需要双指针 afaik。但我只是猜测,不应该这样做,我不在讨论范围内。

标签: c matrix struct


【解决方案1】:

如果您想分配一个num_vert*n 矩阵(其中num_vertn 是从文件中读取的),您或许应该在尝试用一些值填充矩阵之前完成分配工作……

GRAFO *grafo_aux = (GRAFO*) malloc(sizeof(GRAFO));
grafo_aux->arestas = malloc(num_vert * sizeof(struct aresta*));

for ( i = 0 ; i < num_vert ; i++ ){
   grafo_aux->arestas[i] = malloc(n * sizeof(struct aresta));//allocate
   for( j = 0 ; j < n ; j++ ){
      grafo_aux->arestas[i][j].adj  = some_int_value;   //populate
      grafo_aux->arestas[i][j].peso = some_float_value; //populate
      }
}

【讨论】:

  • 我将您的代码与我在这里的代码混合在一起,效果很好!使用 structs 真的很棘手,非常感谢您的正确教学!
  • @Louise Martins,二维数组必须在两个维度上分配。祝你好运!
猜你喜欢
  • 1970-01-01
  • 2018-03-07
  • 2010-11-20
  • 2021-08-27
  • 1970-01-01
  • 2022-08-20
  • 1970-01-01
  • 1970-01-01
  • 2011-06-11
相关资源
最近更新 更多