簡體   English   中英

圖的鄰接矩陣

[英]Adjacency Matrix of Graph

我正在編寫用於實現圖形的鄰接矩陣的代碼,但是卻遇到運行時錯誤,有人可以建議我錯了嗎?

碼:

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

struct Graph{
    int V;
    int E;
    int **Adj;
};

void test(struct Graph *graph)
{
    graph->E = 5;
    graph->V = 4;
    graph->Adj = malloc(sizeof(graph->V * graph->V));
    graph->Adj[0][0] = 9;
    graph->Adj[0][1] = 7;
    graph->Adj[0][2] = 2;
    graph->Adj[0][3] = 5;
    printf("Hello %d\n",graph->Adj[0][2]);    
}
int main()
{
    struct Graph *graph = malloc(sizeof(struct Graph));
    test(graph); 
}

如果我在main函數中執行相同的操作,它將起作用。我不明白編寫測試函數並執行操作時會做錯什么?

在主要功能中完成時的代碼:

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

struct Graph{
    int V;
    int E;
    int **Adj;
};


int main()
{
    struct Graph *graph = malloc(sizeof(struct Graph));
    graph->E = 5;
    graph->V = 4;
    graph->Adj = malloc(sizeof(graph->V * graph->V));
    graph->Adj[0][0] = 9;
    graph->Adj[0][1] = 7;
    graph->Adj[0][2] = 2;
    graph->Adj[0][3] = 5;
    printf("Hello %d\n",graph->Adj[0][2]);

}

獲取運行時錯誤。在調試test function它會一直運行到graph- graph->Adj = malloc(sizeof(graph->V * graph->V)); graph graph->Adj = malloc(sizeof(graph->V * graph->V)); 但是在graph->Adj[0][0] = 9; 它給出了錯誤。為什么?

您正在執行錯誤的malloc。 您正在使用指針指向指針。 因此,您必須首先malloc才能動態分配數組指針。 然后,您將不得不為每一行分配它。

嘗試這個:

 graph->Adj = (int **)malloc(graph->v * sizeof(int *));
    for (i=0; i<graph->v; i++)
         graph->Adj[i] = (int *)malloc(graph->v * sizeof(int));

暫無
暫無

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

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