简体   繁体   English

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

[英]C++ 2d array runtime error

doing some assignment, here's a function to count negative numbers in a dynamically allocated 2D array: 做一些分配,这是一个在动态分配的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++;
            }
        }
    }

Seems legit to me, but the debugger throws this error: 对我来说似乎合法,但是调试器会抛出此错误:

Unhandled exception at 0x00C25D9A in *.exe: 0xC0000005: Access violation reading location 0xCDCDCDCD. * .exe中0x00C25D9A的未处理异常:0xC0000005:访问冲突读取位置0xCDCDCDCD。

Please, help 请帮忙

Here's more code on how I casted it 这是我如何投射的更多代码

    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)

Your initialisation problem is here: 您的初始化问题在这里:

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

You are using x as the array index, while your (probably) mean i . 您正在使用x作为数组索引,而您(可能)的意思是i Your current code just creates an array for the last element, x times. 您当前的代码只是为最后一个元素创建一个数组x次。 Change it to: 更改为:

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

You may also want to adjust this code: 您可能还需要调整以下代码:

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

To: 至:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM