Scott
Scott

Reputation: 13

Crash when accessing matrix in C++

I'm trying to create a 2D array to represent a weighted graph. To make the matrix I am making an array of arrays, as shown in the constructor below. This matrix will store the weight of the edges connecting two nodes. For example graph[1][2] would store the weight of the edge between points 1 and 2.

Weighted_graph::Weighted_graph( int n ):vertices(n){
double **graph= new double *[vertices];
nodeDegree=new int [n];
edges=0;
for (int c=0;c<vertices;c++)
{       
    graph[c] = new double[vertices];
    nodeDegree[c]=0;    
    for (int d=0;d<vertices;d++)
    {   
        graph[c][d]=INF;
    }   
}

}

with graph defined as double **graph;

This seems to work until I try to access the variable graph from other functions at which point the program crashes. (INF is properly defined further down in the code).

Upvotes: 1

Views: 167

Answers (3)

Karl Knechtel
Karl Knechtel

Reputation: 61515

Don't reinvent the wheel. Use boost::multi_array.

Upvotes: 0

tmiddlet
tmiddlet

Reputation: 296

It's all about scope, because you are in a function you can re-use a variable name, but this one is only accessible in the instructor. Remove the double** from in front of graph in the constructor.

Upvotes: 0

Marcus Borkenhagen
Marcus Borkenhagen

Reputation: 6656

I presume you are referencing the graph member of the object you are constructing. However, graph is declared as a local variable there.

Upvotes: 1

Related Questions