C++2d数组运行时错误



在进行一些赋值时,这里有一个函数来计算动态分配的2D数组中的负数:

 void numberOfNegs(int** arrayPointer, int n) {
    int counter{ 0 };
    for (int i{ 0 }; i < n; i++){
        for (int j{ 0 }; j < n; j++){
            if (arrayPointer[i][j] < 0) {
                counter++;
            }
        }
    }

对我来说似乎是合法的,但调试器抛出了这个错误:

*.exe中0x00C25D9A处未处理的异常:0xC0000005:访问读取位置0xCDCDCDCD时发生冲突。

请帮助

以下是我如何铸造的更多代码

    std::cin >> x;
int** theMatrix = new int*[x];
for (int i{ 0 }; i < x; i++){
    theMatrix[x] = new int[x];
}
std::cout << "Please enter a matrix " << x << std::endl;
for (int i{ 0 }; i < x; i++) {
    for (int j{ 0 }; j < x; j++) {
        std::cin >> theMatrix[x][x];
    }
}
 numberOfNegs(theMatrix, x)

您的初始化问题就在这里:

for (int i{ 0 }; i < x; i++){
    theMatrix[x] = new int[x];
}

您使用x作为数组索引,而您的(可能)平均值为i。您当前的代码只是为最后一个元素x次创建一个数组。更改为:

for (int i{ 0 }; i < x; i++){
    theMatrix[i] = new int[x];
}

您可能还想调整此代码:

for (int i{ 0 }; i < x; i++) {
    for (int j{ 0 }; j < x; j++) {
        std::cin >> theMatrix[x][x];
    }
}

收件人:

for (int i{ 0 }; i < x; i++) {
    for (int j{ 0 }; j < x; j++) {
        std::cin >> theMatrix[i][j];
    }
}

最新更新