隣接関係リストをゼロから作成する際に、構造体の配列のアドレス指定とメモリ割り当てに問題があります。 (有向/無向リストを無視する)。
数時間のデバッグの後、私はコードが隣接リストの最後の2つの入力だけを保持していることを発見しました。
実際に私がメモリの割り当てを混乱させ、それにアクセスしていることを何で、どのように知りたいのですか。
このトピック/問題に関するさらに詳しい調査リンクを忘れずにください。前もって感謝します。私はコメントとして述べたようにここで
は私のコード -構造体配列のアドレス指定とメモリの割り当て
/*a single node of an adjacency list*/
typedef struct adjList{
int dest;
struct adjList *next;
} adjList;
/*Image of a graph...*/
typedef struct Image{
int source;
adjList *head;
} Image;
void add_adj_edge(Image graph[], int source, int destiny);
int main() {
int vertices = 6;
Image graph[vertices];
//need not to mention detailed here
// initialize_graph(graph, vertices);
add_adj_edge(graph, 1, 2);
add_adj_edge(graph, 1, 4);
add_adj_edge(graph, 1, 5);
add_adj_edge(graph, 1, 6);
print_graph(graph, vertices);
printf("graph[1].head->dest: %d\n", graph[1].head->dest);
return 0;
}
void add_adj_edge(Image *graph, int src, int dest){
adjList *cache = malloc(sizeof(adjList));
/*create a single node*/
cache->dest = dest;
cache->next = NULL;
if(graph[src].head == NULL){
graph[src].head = cache;
}
else{
while(graph[src].head->next != NULL){
graph[src].head = graph[src].head->next;
}
graph[src].head->next = cache;
}
return;
}
出力
node: 1 5 6
node: 2
node: 3
node: 4
node: 5
node: 6
graph[1].head->dest: 5
Instead of
node: 1 2 4 5 6
node: 2
node: 3
node: 4
node: 5
node: 6
graph[1].head->dest: 2
'グラフ[SRC] .head =グラフ[SRC] .head-> next'。それは間違いです。リストをトラバースするには、一時変数を使用する必要があります。各反復でヘッドポインタを変更しないでください。 – kaylum
最初に 'Image graph [vertices];'を割り当てたが、決して '..head = NULL;'を設定していないので、 'if(graph [src] .head == NULL) add_adj_edge() 'は常に' false'です。 –
@ J.Piquard 'initialize_graph(グラフ、頂点)'に 'NULL'に各ヘッドを割り当てました – ph03n1x