将 malloc 替换为数组

Replace malloc with array

本文关键字:数组 替换 malloc      更新时间:2023-10-16

我有一个图像处理程序(canny-edge-detection(,这是代码的一部分:

short int **magnitude;
int rows=320, cols=240;
//Allocate memory to store the image, warning if not successful
if((*magnitude = (short *) calloc(rows*cols, sizeof(short))) == NULL){
//some warning
}

我想使用数组来避免动态分配内存,因为这在我将要运行代码的系统中是不可行的。在这种情况下,数组的大小是多少?我假设

short int magnitude_arr[76800]

但是,输出图像被切成两半。

您的声明将为您提供一个具有正确大小的静态大小数组。 如果您的程序不再工作,则错误在其他地方。

如果您打算使用静态大小,您可能会考虑使用

std::array<short, 76800u> magnitude;

std::vector<short> magnitude(rows * cols);

如果相反,行和列可能会更改以使运行时大小动态。

如果需要指向存储数据的指针,这两个类都具有data()成员函数。

这应该做得很好。

const int rows=320;   
const int cols=240;
short int magnitud_arr[rows * cols];