程序崩溃与数组声明

时间:2017-11-27 08:37:04

标签: c++ arrays

我有一个奇怪的问题。这是我的代码:

#include <iostream>
#include "opencv2/opencv.hpp"
#include <stdint.h>

using namespace cv;

int main()
{
Mat img = imread("testbild.jpg", CV_LOAD_IMAGE_UNCHANGED);

Mat imgGray = imread("testbild.jpg", CV_LOAD_IMAGE_GRAYSCALE);

if (img.empty())
{
    std::cout << "Kein Bild gefunden!" << std::endl;
}

//This array isn't used for while but I will use it in the future
int intensity[imgGray.rows] [imgGray.cols];

int max;

for (int r = 0; r <= imgGray.rows; r++)
{
    for (int c = 0; c <= imgGray.cols; c++)
    {

        if (max < (int)imgGray.at<uint8_t> (r,c))
        {
            max = (int)imgGray.at<uint8_t> (r,c);
        }

    }
}

std::cout << max << std::endl;

return 0;
}
事情是,cout不起作用。我不知道为什么。但每当我发表评论时

int intensity[imgGray.rows] [imgGray.cols];

再次有效。

我知道这条线还没有使用,但我稍后会用到它。

为什么会这样?我是编程的新手所以请不要生气,如果这是一个非常简单的答案。我也已经使用谷歌找到了解决方案,但我得到的只是刷新输出,这不起作用。

顺便说一句,控制台是打开的,但它只是说“按此按钮关闭此窗口......”。

1 个答案:

答案 0 :(得分:-2)

原因是当大小不是常数时,你不能像这样声明你的数组。您需要动态分配它。

一种方法是:

int** intensity; //double pointer used to make 2D array
intensity = new int*[imgGray.rows]; //The double pointer now points to an array of single pointer.
for (int i = 0; i < imgGray.rows; ++i) //for each pointer in the array, create an array of integer, effectively a 2D array.
    intensity[i] = new int[imgGray.cols];

之后,您可以通过intensity[i][j]访问2D数组中的单个值,但确保它永远不会超出限制是您的工作,您需要在完成后自行释放内存。 (除非你在那之后立即关闭程序,否则它很好)

相关问题