簡體   English   中英

分配結構矩陣的內存結構

[英]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_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
      }
}

暫無
暫無

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

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