2009-02-09 69 views
3

一个动态地分配二维数组,这个问题建立掀起了以前问的问题: Pass by reference multidimensional array with known sizeC++引用传递

我一直在试图找出如何让我的功能与二维数组引用发挥很好。我的代码的简化版本如下:

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类型**通过引用这样我可以在一个函数中为数组分配空间,并在另一个函数中设置值。

回答

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 
}; 
3
typedef array_type unsigned int **; 
initialize_BMP_array(array_type& bmparray, int height, int width) 
1

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

void initialize_BMP_array(vector<vector<unsigned int> > &bmparray, int height, int width); 
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存储器是在函数内部保留(然后,通过以引用的)。

希望这会有所帮助。

+0

如果我有一个功能,我使用malloc和指针分配一些内存传递对象,其实我延伸的阵列。现在,我必须使用return来传递相同的数组。现在,在我返回之前,我甚至无法释放它。在这种情况下,我可以做什么? – 2012-10-18 17:13:06

+0

您必须编写这两个函数,以便接收分配数组的函数在此之后释放它。也就是说,接收分配值的函数必须知道它必须释放它。 – 2012-10-18 20:31:33