私はグラフが初めてで、グラフで非常に単純なプログラムを作成しようとしています。私は 2 つの関数を作成しました。そのうちの 1 つは、ユーザーが入力した数の頂点を持つ空のグラフを作成します。もう 1 つは、2 つの頂点間に有向エッジを追加します。
前者は正常に実行されますが、後者は実行されません。プログラムは実行を停止しますが、コードは正常にコンパイルされます。
#include <stdio.h>
#include <stdlib.h>
#define MAX 1000
struct node
{
int data;
struct node *next;
};
struct node *arr[MAX];
void createEmptyGraph(int n)
{
// n is the number of vertices
int i;
for(i=0;i<n;i++)
{
arr[i]=NULL;
}
printf("\nAn empty graph with %d vertices has been created",n);
printf("\nNo edge is connected yet");
}
void addNode(int startVertex,int endVertex)
{
// For directed edges
struct node *n;
n=(struct node *)malloc(sizeof(struct node));
n->next=arr[startVertex];
arr[startVertex]->next=n;
printf("\nAn edge between directed from %d to %d has been added",startVertex,endVertex);
}
int main(void)
{
int num;
printf("Enter the number of vertices in the graph: ");
scanf("%d",&num);
createEmptyGraph(num);
addNode(0,1);
return 0;
}
グラフの隣接リスト表現を使用しています。エラーを指摘してください。
メソッドでもう1つcreateEmptyGraph()
、なぜこのようなことができないのですか
for(i=0;i<n;i++)
{
arr[i]->data=d;
arr[i]->next=NULL;
}