简体   繁体   中英

Adjacency matrix graph representation code crashing

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;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM