#include<stdio.h>
#include<stdlib.h>
struct Graph{
int V;
int E;
int **Adj;
};
struct Graph* adjMatrix(){
int u,v,i;
struct Graph *G;
G=(struct Graph*)malloc(sizeof(struct Graph));
if(!G){
printf("Memory Error!\n");
return;
}
printf("Enter number of nodes and number of edges:\n");
scanf("%d %d",&G->V,&G->E);
G->Adj=malloc((G->V)*(G->V)*sizeof(int));
for(u=0;u<(G->V);u++)
for(v=0;v<(G->V);v++)
G->Adj[u][v]=0; //This gives a segmentation fault.
printf("Enter node numbers in pair that connect an edge:\n");
for(i=0;i<(G->E);i++){
scanf("%d %d",&u,&v);
G->Adj[u][v]=1;
G->Adj[v][u]=1;
}
return(G);
}
int main(){
struct Graph *G;
int i,j,count=0;
G=adjMatrix();
for(i=0;i<G->V;i++){
for(j=0;j<G->V;j++){
printf("%d ",G->Adj[i][j]);
count++;
}
if(count==G->V)
printf("\n");
}
return 0;
}
The code shows segmentation fault when I tried to assign a value in 2D array i.e. at G->Adj[u][v]=0; but I don't know what is wrong with that? Because It's simply a assignment to the array.