【问题标题】:Replace malloc with array用数组替换 malloc
【发布时间】:2018-10-14 23:09:59
【问题描述】:

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

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

【问题讨论】:

  • 这里唯一可以确定的就是数组的大小肯定是76800,或者rows*cols
  • short int magnitude_arr[320*240]; 是正确的,也许你在程序的其他地方犯了错误

标签: c++ canny-operator


【解决方案1】:

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

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

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

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

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

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

【讨论】:

    【解决方案2】:

    这应该做得很好。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-08
      • 2014-01-06
      • 1970-01-01
      • 2023-04-04
      • 2011-11-05
      • 2012-01-26
      • 1970-01-01
      • 2021-12-25
      相关资源
      最近更新 更多