MEMSET FUCTION在我的C 动态阵列初始化中不起作用

memset fuction does not work in my c++ dynamic array initialization

本文关键字:阵列 初始化 不起作用 动态 FUCTION 我的 MEMSET      更新时间:2023-10-16

我的OpenCV图像处理代码的某些部分。在IT上,我生成了两个动态数组来存储二进制图像中每个Col/Row的黑点的总数。 这是代码:

#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main()
{
    Mat srcImg = imread("oura.bmp");
    width = srcImg.cols - 2;
    height = srcImg.rows - 2;
    Mat srcGrey;
    Mat srcRoi(srcImg, Rect(1, 1, width, height));
    cvtColor(srcRoi, srcGrey, COLOR_BGR2GRAY);
    int thresh = 42;
    int maxval = 255;
    threshold(srcGrey, srcRoiBina, thresh, maxval, THRESH_BINARY);
    int *count_cols = new int[width] ();
    int *count_rows = new int[height] ();
    for (int i = 0; i < width; i++)
    {
        cout << count_cols[i] << endl;
    }
    for (int i = 0; i < height; i++)
    {
        uchar *data = srcRoiBina.ptr<uchar>(i);
        for (int j = 0; j < width; j++)
        {
            if (data[j] == 0)
            {
                count_cols[j]++;
                count_rows[i]++;
            }       
        }
    }
    delete[] count_cols;
    delete[] count_rows;
    return 0;
}

我的问题是:如果我使用以下代码

    int *count_cols = new int[width];
    int *count_rows = new int[height];
    memset(count_cols, 0, sizeof(count_cols));
    memset(count_rows, 0, sizeof(count_rows));
    for (int i = 0; i < width; i++)
    {
        cout << count_cols[i] << endl;
    }

要替换下面的相应代码,为什么动态数组不能初始化为零?似乎MEMSET不起作用。

平台:Visual Stdio 2013 OpenCV 3.0.0

你能帮我吗?

此外,原始图像outa.bmp是2592*1944。有一些潜在的问题吗?

count_colsint*类型,因此sizeof(count_cols)为8(64位)或4(32bit)。您需要使用sizeof(int) * width(类似地用于行)。

sizeof(count_rows)正在返回指针的大小,而不是数组的大小。

改用height * sizeof(int)。同样适用于列。