首页 > 解决方案 > 用数组替换 malloc

问题描述

我有一个图像处理程序(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]

然而,输出图像被削减了一半。

标签: c++canny-operator

解决方案


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

如果您打算使用静态尺寸,您可能会考虑使用

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

或者

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

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

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


推荐阅读