3

这个问题建立在先前提出的问题之上: Pass by reference multidimensional array with known size

我一直在试图弄清楚如何让我的函数与 2d 数组引用很好地配合使用。我的代码的简化版本是:

    unsigned int ** initialize_BMP_array(int height, int width)
    {
       unsigned int ** bmparray;
       bmparray = (unsigned int **)malloc(height * sizeof(unsigned int *));
       for (int i = 0; i < height; i++)
       {
        bmparray[i] = (unsigned int *)malloc(width * sizeof(unsigned int));
       }
      for(int i = 0; i < height; i++)
        for(int j = 0; j < width; j++)
        {
             bmparray[i][j] = 0;
        }
    return bmparray;
    }

我不知道如何重写此函数,以便它可以在我通过引用将 bmparray 作为空的 unsigned int ** 传入的地方工作,以便我可以在一个函数中为数组分配空间,并设置值在另一个。

4

4 回答 4

3
typedef array_type unsigned int **;
initialize_BMP_array(array_type& bmparray, int height, int width)
于 2009-02-09T21:03:11.410 回答
3

使用一个类来包装它,然后通过引用传递对象

class BMP_array
{
public:
    BMP_array(int height, int width)
    : buffer(NULL)
    {
       buffer = (unsigned int **)malloc(height * sizeof(unsigned int *));
       for (int i = 0; i < height; i++)
       {
        buffer[i] = (unsigned int *)malloc(width * sizeof(unsigned int));
       }

    }

    ~BMP_array()
    {
        // TODO: free() each buffer
    }

    unsigned int ** data()
    {
        return buffer;
    }

private:
// TODO: Hide or implement copy constructor and operator=
unsigned int ** buffer
};
于 2009-02-09T21:12:38.627 回答
2

嗯......也许我不太理解你的问题,但在 C 中你可以通过传递另一个指针间接级别来传递“通过引用”。也就是说,指向双指针 bmparray 本身的指针:

unsigned int ** initialize_BMP_array(int height, int width, unsigned int *** bmparray)
{
   /* Note the first asterisk */
   *bmparray = (unsigned int **)malloc(height * sizeof(unsigned int *));

   ...

   the rest is the same but with a level of indirection


   return *bmparray;
}

所以 bmparray 的内存被保留在函数内部(然后,通过引用传递)。

希望这可以帮助。

于 2009-02-09T21:09:00.570 回答
1

要使用更安全、更现代的 C++ 习惯用法,您应该使用向量而不是动态分配的数组。

void initialize_BMP_array(vector<vector<unsigned int> > &bmparray, int height, int width);
于 2009-02-09T21:06:43.150 回答