I am new to graphs and I am trying to write very simple programs in graph. I have written two functions, one of which creates an empty graph with as many vertices as inputted by the user. The other one, adds a directed edge between two of the vertices.
The former executes successfully, but the later does not. The program stops running, however the code compiles successfully.
#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;
}
I am using adjacency list representation of graphs. Please point out the errror(s).
One more thing, in the createEmptyGraph() method, why can’t I do something like this
for(i=0;i<n;i++)
{
arr[i]->data=d;
arr[i]->next=NULL;
}
You declare an array of pointers:
In your
createEmptyGraph()method, you need to allocate each structure in the array first – instead you are setting simply the pointer to null..The following won’t work because you’ve not allocated each entry:
Allocate first (
malloc()) and then you can set as above…So, because of the fact that you’ve not allocated, the following will not work: