Tengo una clase que tiene como atributo una matriz bidimensional dinámica:
int **terrain;
La matriz la genero de la siguiente forma:
void Terrain::generateTerrain() {
terrain = new int *[rows];
for (int i = 0; i < rows; i++) {
terrain[i] = new int[cols];
for (int j = 0; j < cols; j++)
terrain[i][j] = 0;
}
}
Creo un método getter
a la matriz:
int **Terrain::get_terrain() const {
return terrain;
}
Los valores de la matriz son tomados de un archivo, en otra clase:
Terrain *Gui::readFileAndLoadData(std::string *path) {
string line;
ifstream ifile(*path);
int rows, cols, max, ground_desired, x_tractor, y_tractor;
// Codigo para dar valor a las variables anteriores
Terrain terrain(rows, cols, max, ground_desired, x_tractor, y_tractor);
Terrain *terrain_ptr = &terrain;
terrain_ptr->generateTerrain();
int **terrain_representation = terrain_ptr->get_terrain();
for (int i = 0; i < terrain.get_rows(); i++) {
vector<string> new_line;
getline(ifile, line);
istringstream input(line);
copy(istream_iterator<string>(input),
istream_iterator<string>(),
back_inserter(new_line));
for (int j = 0; j < terrain.get_cols(); j++) {
terrain_representation[i][j] = stoi(new_line[j]);
}
}
return terrain_ptr;
}
Si justo antes del return
intento mostrar por pantalla los valores de terrain_representation
no habría ningún problema. El problema viene cuando lo intento hacer desde otra clase donde tengo el método main
. En este método tengo lo siguiente:
int main() {
Gui gui; // clase donde esta el metodo anterior
std::string str = "./terrain.txt";
std::string *ptr = &str;
Terrain *terrain = gui.readFileAndLoadData(ptr);
cout << terrain->get_terrain()[1][0] << endl;
cout << terrain->get_terrain()[0][0] << endl;
cout << terrain->get_terrain()[2][0] << endl;
cout << terrain->get_terrain()[3][0] << endl;
return 0;
}
Llegados a este punto, los valores en las posiciones [1][0], [2][0] y [3][0] son los correctos, pero al mostrar el valor de [0][0] (o cualquier columna de la fila 0), da un valor totalmente desorbitado:
6
-1764852856
2
4
El valor correcto sería 6, en este caso. Pero aun me desconcierta más que si cambio el orden de los cout
por el siguiente, salta un Segmentation fault (core dumped)
. ¿A qué se debe esto?
cout << terrain->get_terrain()[0][0] << endl;
cout << terrain->get_terrain()[1][0] << endl;
cout << terrain->get_terrain()[2][0] << endl;
cout << terrain->get_terrain()[3][0] << endl;