I was implementing a graph program based on an adjacency matrix in C. But I am getting a segmentation fault while I am initializing the matrix (assigning the value of zero). I am not sure whether I am doing any mistake in accessing double pointers or not.
Can anyone please help me in resolving the issue?
Here is the code:
struct Graph {
int V;
int E;
int **adj;
};
struct Graph *addelements() {
int i,j,a,u,v;
struct Graph *G= (struct Graph*)malloc(sizeof(struct Graph*));
printf("Enter the number of vertices and edges : ");
scanf("%d %d", &G->V,&G->E);;
printf("%d, %d\n",G->V ,G->E);
//G->adj = (int **)malloc(sizeof(int **)*(G->V * G->E));
G->adj = malloc(sizeof(G->V * G->E));
//Initialization of vertices
for(i=0;i<=G->V;i++) {
for(j=0;i<=G->V;j++) {
G->adj[i][j]=0;
}
}
//Reading the edges;
for(i=0;i<G->E;i++) {
printf("Enter the source and destination : ");
scanf("%d %d\n", &u,&v);
G->adj[u][v]=1;
G->adj[v][u]=1;
}
//printing the matrix
for(i=0;i< G->V;i++) {
for(j=0;i< G->V;j++) {
printf("%d", G->adj[i][j]);4
}
}
return G;
}
int main() {
struct Graph *a= (struct Graph*)malloc(sizeof(struct Graph*));
a = addelements();
}
The output:
Enter the number of vertices and edges : 4 5
Segmentation fault (core dumped)