[英]Allocate memory struct of a struct matrix
我的結構是:
typedef struct grafo GRAFO;
struct aresta {
int adj;
float peso;
};
struct grafo {
struct aresta **arestas;
};
我無法像這樣分配矩陣 arestas:
GRAFO *grafo_aux = (GRAFO*) malloc(sizeof(GRAFO));
grafo_aux->arestas = malloc(num_vert * sizeof(struct aresta*));
正確的代碼是什么? 謝謝!
如果你想分配一個num_vert*n
矩陣(其中num_vert
和n
是從文件中讀取的)你應該在嘗試用一些值填充矩陣之前完成分配工作......
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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.