1
我已經開始學習C++了,而且我遇到了問題。我的程序將從命令行獲取4個參數。這些參數將是兩個多維數組的維數。 ./myprogram 2 2 2 2
嘗試讀取第二個多維數組時出現分段錯誤
這是我進入第一個2x2的數組中的元素:
1 2 3 4
然後我進入元素的第二陣列: 5
然後我得到了一個錯誤終端說明Segmentation fault (core dumped)
這裏是從命令行和輪胎讀取的代碼s到的數組元素爲:
#include <iostream>
#include <stdlib.h>
using namespace std;
void readArr(int, int, double**);
int main(int argc, char* argv[]) {
int aRowCount = atoi(argv[1]);
int aColCount = atoi(argv[2]);
int bRowCount = atoi(argv[3]);
int bColCount = atoi(argv[4]);
std::cout << "Input accepted" << endl;
if(aColCount != bRowCount) {
std::cerr << "Col. Count of the first must match Row. Count of the second matrix." << endl;
return 1;
}
double **A = new double*[aRowCount];
for(int i = 0; i < aRowCount; i++){
A[i] = new double(aColCount);
}
std::cout << "allocating A" << endl;
double **B = new double*[bRowCount];
for(int j = 0; j < bRowCount; j++){
A[j] = new double(bColCount);
}
std::cout << "allocating B" << endl;
double **C = new double*[aRowCount];
for(int k = 0; k < aRowCount; k++) {
C[k] = new double(bColCount);
}
std::cout << "Reading in A" << endl;
readArr(aRowCount, aColCount, A);
std::cout << "Reading in B" << endl;
readArr(bRowCount, bColCount, B);
return 0;
}
void readArr(int rowCount, int colCount, double **array) {
for(int i = 0; i < rowCount; i++) {
for(int j = 0; j < colCount; j++) {
std::cin >> array[i][j];
}
}
}
什麼過程導致決定使用'new'和'double **'?這值得重溫。 –
您使用原始數組和指針會使您的代碼難以閱讀並且容易出錯。而你錯過了所有'delete []'s。幸運的是,你可以使用'std :: vector'而不是原始數組。它可以完成'new []'所做的一切,但是以更好更安全的方式進行。 –
你也應該使用'std :: stoi'來代替同樣容易出錯的'atoi'函數。 –