Reputation: 655
I wrote the following code for Adjacency matrix graph representation but code is not working. I think there is some problem in line 25 but i am not able to debug it. Please point out the problem in code. Thanks
#include<iostream>
#include<cstdlib>
using namespace std;
struct Graph{
int V;
int E;
int **adj;
};
struct Graph* adjMatrixForGraph(int vertices,int edges){
int i,j;
Graph *G=(struct Graph*) malloc(sizeof(struct Graph));
//Graph *G=new Graph();
if(!G){
cout<<"Memory error";
}
G->V=vertices;
G->E=edges;
G->adj =(int **) malloc(sizeof(G->V*G->V));
//G->adj =new int*;
for(i=0;i<G->V;i++){
for(j=0;j<G->V;j++){
*(*(G->adj+j)+j)=0;
}
}/*
for(int u=0;u<G->E;u++){
cin>>i>>j;
G->adj[i][j]=1;
G->adj[j][i]=1;
}*/
return G;
}
int main(){
Graph *G=NULL;
G=adjMatrixForGraph(4,4);
return 0;
}
Upvotes: 0
Views: 365
Reputation: 126
You do not allocate a two dim array by
G->adj =(int **) malloc(sizeof(G->V*G->V));
Instead, you should do
G->adj =(int **) malloc(G->V*sizeof(int*));
for (int i = 0; i < G->V; ++i) {
*(G->adj+i) = (int*) malloc(G->V*sizeof(int));
}
BTW, it might be more efficient for you to use 1-d array to simulate 2-d array because memory access can be slower than index computation. But that can be another story.
Upvotes: 2