分配结构矩阵的内存结构

时间:2016-04-29 20:05:07

标签: c matrix struct

我的结构是:

typedef struct grafo GRAFO;
struct aresta {

    int adj; 
    float peso;
};

struct grafo {
    struct aresta **arestas;
};

我无法管理malloc像矩阵那样:

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

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

1 个答案:

答案 0 :(得分:0)

如果您想要分配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
      }
}
相关问题