试图在第二个多维阵列中读取时会发生分割故障



我已经开始学习C ,并且我已经有一个问题。我的程序将从命令行中获取4个参数。这些参数将是两个多维阵列的维度。 ./myprogram 2 2 2 2

这就是我输入第一个2x2数组的元素的方式:

1 2 3 4

然后我输入第二个数组的元素: 5

然后,我在终端中遇到了一个错误,说明Segmentation fault (core dumped)

这是从命令行读取的代码和轮胎以在数组元素中读取:

#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];
        }
    }
}

this:

    A[i] = new double(aColCount);

应该是:

    A[i] = new double[aColCount];

和其他地方类似。您的代码分配A double,并以aColCount的值进行初始化。

相关内容

  • 没有找到相关文章

最新更新