Estoy tratando de asignar una matriz 2D dentro de AllocateMatrix y devolverla, pero cuando uso la matriz 2D devuelta, aparece un error de segmento. Mi pregunta es, ¿por qué falla la segmentación y cómo lo soluciono para que pueda pasarlo y usarlo en otras funciones? fileTest es solo un archivo txt con la siguiente fila, la siguiente línea, la columna, la siguiente línea y luego la matriz con un espacio en cada columna y una nueva línea para cada fila.
class Matrix
{
public:
Matrix();
~Matrix();
double** AllocateMatrix(unsigned rows, unsigned columns);
Matrix(std::string filePath);
private:
unsigned rows_;
unsigned columns_;
};
Matrix::Matrix(std::string filePath)
{
std::ifstream matrixFile;
try
{
matrixFile.open(filePath);
if(matrixFile.fail())
throw "Failed to open file.";
std::cout << "Starting read file...\n";
matrixFile >> rows_;
std::cout << "rows: " << rows_ << "\n";
if(rows_ < 0)
throw "Number of rows cannot be negative.";
matrixFile >> columns_;
std::cout << "columns: " << columns_ << "\n";
if(columns_ < 0)
throw "Number of columns cannot be negative.";
double** array2D;
array2D = AllocateMatrix(rows_, columns_);
for(uint64_t i = 0; i < rows_; i++)
{
for(uint64_t j = 0; j < columns_; j++)
{
std::cout << i << " " << j << " " << array2D[i][j] << "\n"; // seg fault here
}
}
std::cout << "Finished file read" << std::endl;
matrixFile.close();
}
catch(const char* message)
{
std::cerr << message << std::endl;
rows_ = 0;
columns_ = 0;
return;
}
}
double** Matrix::AllocateMatrix(unsigned rows, unsigned columns)
{
try
{
double** matrix = new double *[rows];
for(unsigned i = 1; i <= rows; i++)
{
matrix[i] = new double[columns];
}
for(unsigned i = 1; i <= rows; i++)
{
for(unsigned j = 1; j <= columns; j++)
{
matrix[i][j] = 0;
std::cout << "i: " << i << " j: " << j << " value: " << matrix[i][j] << "\n";
}
}
matrix = result_;
std::cout << "Returning 2D Array\n";
return matrix;
}
catch(const std::bad_alloc&) {
std::cerr << "Bad allocation." << std::endl;
return nullptr;
}
}
int main()
{
Matrix matrixOne("fileTest.txt");
return 0;
}
Solución del problema
intente no usar punteros de estilo C, no use punteros de estilo C. su problema es un error de usuario. use std::vector en lugar de usar el doble puntero porque es un gran problema, si lo ha usado, haga esto: double* array2d[array_sz]; en cuanto a no memleak.
No hay comentarios.:
Publicar un comentario