Считывание матрицы из файла C++
Хочу написать программу, которая выполняет матричные преобразования (сумма двух матриц, умножение, вычитание и т.д.), но застряла на этапе со считывнием матрицы. Выдает ошибку: "Вызвано исключение: нарушение доступа для чтения. m.data было 0x1110112." Код:
#include <iostream>
#include <fstream>
//создаем структуру
struct Matrix {
int** data = 0;
size_t rows = 0;
size_t cols = 0;
};
//функция, которая выделяет место для матрицы в динамической памяти и заполняет её
bool Allocate(Matrix& m) {
//если матрица пустая, то заполняем её
if (!m.data) {
//выделяем место
m.data = new int* [m.rows];
for (size_t i = 0; i < m.rows; i++) {
m.data[i] = new int[m.cols];
}
//заполняем нулями
for (size_t y = 0; y < m.rows; y++) {
for (size_t x = 0; x < m.cols; x++)
m.data[x][y] = 0;
}
return true;
}
return false;
}
//функция для удаления матрицы из памяти
bool Deallocate(Matrix& m) {
if (m.data) {
for (size_t y = 0; y < m.rows; y++) {
delete[] m.data[y];
}
delete[] m.data;
m = Matrix();
return true;
}
return false;
}
//вывести матрицу
void outputMatrix(std::ostream& out, const Matrix& m) {
out << m.rows << ' ' << m.cols << '\n';
for (size_t y = 0; y < m.rows; y++) {
for (size_t x = 0; x < m.cols; x++) {
out << m.data[y][x] << ' ';
}
out << '\n';
}
}
//считывание матрицы из файла
bool inputMatrix(std::istream& in, Matrix& m) {
Matrix result;
//из первой строчки файла считываем количество строк и столбцов
in >> result.rows >> result.cols;
if (!result.rows || !result.cols) {
std::cerr << "wrong\n";
return false;
}
bool readResult = true;
if (Allocate(result)) {
//если мы создали матрицу
for (size_t y = 0; y < result.rows; y++) {
for (size_t x = 0; x < result.cols; x++) {
//то итерируемся по строкам и столбцам
if (readResult && in) {
//и если матрица считана, то заполняем матрицу значениями из файла
in >> m.data[x][y];
}
else {
std::cerr << "error reading matrix form\n";
readResult = false;
}
}
}
}
if (readResult) {
m = result;
}
else {
Deallocate(m);
}
return readResult;
}
bool Sum(Matrix& dst, Matrix& lft, Matrix& rht) {
if (lft.rows != rht.rows || lft.cols != rht.cols || (dst.data && (dst.rows != lft.rows || dst.cols != lft.cols))) {
return false;
}
bool sumResult = true;
Matrix result = dst;
if (!dst.data) {
result.rows = lft.rows;
result.cols = lft.cols;
sumResult = Allocate(result);
}
if (sumResult) {
for (size_t y = 0; y < result.rows; y++) {
for (size_t x = 0; x < result.rows; x++) {
result.data[x][y] = lft.data[y][x] + rht.data[y][x];
}
}
}
else {
if (!Deallocate(result)) {
std::cerr << "Error while deallocating memory\n";
exit(1);
}
}
return sumResult;
}
Matrix allocateAndRead(const char* filename) {
Matrix result;
std::ifstream fin(filename);
if (!fin) {
std::cerr << "error\n";
return result;
}
if (inputMatrix(fin, result)) {
outputMatrix(std::cout, result);
}
return result;
}
int main() {
std::ifstream fin("input2.txt");
if (!fin) {
std::cerr << "error opening file\n";
return 1;
}
Matrix m;
if (inputMatrix(fin, m)) {
outputMatrix(std::cout, m);
}
return 0;
}