還有其他關於分段錯誤常見原因的帖子,但我不認爲我在這裏創建的內置數組對象(result
)doesn'當我給它賦值時,不會超出範圍。
我認爲這可能對未來的人們有幫助,他們的數組並沒有超出範圍,我也沒有看到很多關於製作二維內置數組對象的東西 - 我見過的例子幾乎都是矢量或std:數組對象。分段錯誤,但數組對象不會出界(C++)
這裏是可運行的,相關代碼:
matrix.h
#ifndef MATRIX_H
#define MATRIX_H
#include <initializer_list>
using std::initializer_list;
typedef unsigned int uint;
class Matrix {
public:
Matrix(uint rows, uint cols);
~Matrix();
Matrix add(double s) const;
const uint numRows() const;
const uint numCols() const;
double & at(uint row, uint col);
const double & at(uint row, uint col) const;
private:
uint rows, cols;
double ** matrix;
void makeArray() {
matrix = new double * [rows];
for(uint i = 0; i < rows; ++i) {
matrix[i] = new double [cols];
}
}
};
#endif
matrix.cpp
#include "matrix.h"
Matrix::Matrix(uint rows, uint cols) {
//Make matrix of desired size
this->rows = rows;
this->cols = cols;
makeArray();
//Initialize all elements to 0
for(uint i = 0; i < rows; ++i) {
for(uint j = 0; j < cols; ++j) {
this->matrix[i][j] = 0.0;
}
}
}
Matrix::~Matrix() {
for(uint i = 0; i < numRows(); ++i) {
delete[] matrix[i];
}
delete[] matrix;
}
const uint Matrix::numRows() const {
return this->rows;
}
const uint Matrix::numCols() const {
return this->cols;
}
double & Matrix::at(uint row, uint col) {
return matrix[row][col];
}
const double & Matrix::at(uint row, uint col) const {
return matrix[row][col];
}
Matrix Matrix::add(double s) const {
uint r = this->numRows();
uint c = this->numCols();
Matrix * result;
result = new Matrix(r, c);
for(uint i = 0; i < r; ++i) {
for(uint j = 0; j < c; ++j) {
result->at(i,j) = (this->at(i,j)) + s;
}
}
return * result;
}
的main.cpp
#include <iostream>
#include <cstdlib>
#include "matrix.h"
using namespace std;
typedef unsigned int uint;
int main() {
Matrix * matrix;
matrix = new Matrix(3, 2); //Works fine
double scaler = 5;
matrix->at(2,1) = 5.0; //Works fine
Matrix r = matrix->add(scaler); //DOESN'T WORK
return EXIT_SUCCESS;
}
任何想法爲什麼add
函數導致分段錯誤錯誤?我用來填充結果Matrix對象的for循環沒有超出範圍,而且我對C++不熟悉,不知道還有什麼可能導致它。
在此先感謝。
可能還有其他問題。不要試圖自己管理動態內存分配,除非您確定需要。 –
我們應該忽略你的add()成員中的內存泄漏,只關注一個更大的問題,即[3是什麼規則](https://stackoverflow.com/questions/4172722/what-is三的規則)? – WhozCraig
'矩陣*結果; [返回]結果;'你爲什麼這樣做?順便說一句我沒有看到任何好的理由在你的代碼中的單個'*' – user463035818