I've built the Graph class, one constructor and one destructor. My problem is: when i compile this code, i get an error at this line delete [] mat[i];
, the error is 'Access violation reading location 0xDDDDDDCD.' and i'm not sure what am i doing wrong. I mean i only delete the memory i dynamically alocated.
Later edit: even if i use this instead of my method :
Graph(int nr_noduri) {
this->nr_noduri = nr_noduri;
mat = new bool* [nr_noduri];
for (int i = 0; i < nr_noduri; i++) {
mat[i] = new bool[nr_noduri];
}
for (int i = 0; i < nr_noduri; i++) {
for (int j = 0; j < nr_noduri; j++) {
mat[i][j] = 0;
}
}
}
My code is :
#include <iostream>
#include <cstdlib>
using namespace std;
class Graph {
bool** mat;
int nr_noduri;
public:
Graph(int nr_noduri) {
this->nr_noduri = nr_noduri;
mat = (bool**)calloc(nr_noduri, sizeof(bool*));
for (int i = 0; i < nr_noduri; i++) {
mat[i] = (bool*)calloc(nr_noduri, sizeof(bool));
}
}
int size() {
return nr_noduri;
}
void addArc(int v, int w) {
if (v < nr_noduri && w < nr_noduri) {
mat[v][w] = true;
}
else cout << "Not enough nodes !" << endl;
}
bool isArc(int v, int w) {
return (mat[v][w] == true);
}
void print() {
for (int i = 0; i < nr_noduri; i++) {
cout << endl;
for (int j = 0; j < nr_noduri; j++) {
cout << mat[i][j] << " ";
}
}
cout << endl;
}
~Graph() {
//cout << nr_noduri;
for (int i = 0; i < nr_noduri; i++) {
delete [] mat[i];
}
delete[] mat;
}
friend void dfs(Graph g, int v, bool vazut[]);
};
void dfs(Graph g, int v, bool vazut[]) {
int w;
vazut[v] = true;
for (w = 0; w < g.size(); w++) {
if (g.isArc(v, w) && !vazut[w]) {
cout << v << "->" << w;
dfs(g, w, vazut);
}
}
}
int main() {
int nr_noduri;
cin >> nr_noduri;
Graph v(nr_noduri);
v.print();
v.addArc(1, 2);
v.addArc(2, 5);
cout << v.isArc(1, 2) << endl;
v.print();
bool vazut[100];
dfs(v, 1, vazut);
return 0;
}