Little Tooth Little Tooth - 1 year ago 98
C++ Question

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

This some parts of my opencv image processing codes.In it, I generate two dynamic arrays to store the total numbers of black points per col/row in binary image.
Here are the codes:

#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)

delete[] count_cols;
delete[] count_rows;
return 0;

My question is that: if I use the follow codes

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;

to replace the corresponding codes below, why the dynamic arrays can not be initialized to zero? It seems that the memset does not work.

Platform: Visual Stdio 2013 + opencv 3.0.0

Could you please help me?

Additionally, the original image oura.bmp is 2592*1944.Thus the length of the dynamic array count_cols is 2590(ie, 2592-2). Is there some potential problems?

Answer Source

count_cols is of type int*, so sizeof(count_cols) will be 8 (64bit) or 4 (32bit). You'll want to use sizeof(int) * width instead (and similarly for rows).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download