【问题标题】:Adjacency matrix graph representation code crashing邻接矩阵图表示代码崩溃
【发布时间】:2015-06-11 06:50:33
【问题描述】:

我为邻接矩阵图表示编写了以下代码,但代码不起作用。我认为第 25 行有一些问题,但我无法调试它。请指出代码中的问题。 谢谢

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

【问题讨论】:

  • c++?在我看来 C.... malloc,struct,只是函数....我认为最好将标签 c++ 更改为 c
  • 这是 C 而不是 C++
  • erm.. C 没有iostream

标签: c algorithm data-structures graph


【解决方案1】:

你没有分配一个两个暗淡的数组

G->adj =(int **) malloc(sizeof(G->V*G->V));

相反,你应该这样做

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

顺便说一句,使用一维数组来模拟二维数组可能更有效,因为内存访问可能比索引计算慢。但这可能是另一回事。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多