C ++按引用传递动态地分配二维数组 [英] C++ Passing a dynamicly allocated 2D array by reference

查看:113
本文介绍了C ++按引用传递动态地分配二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题建立掀起了previously问问题:
<一href=\"http://stackoverflow.com/questions/529109/c-pass-by-reference-multidimensional-array-with-known-size\">Pass通过与已知大小参考多维数组

This question builds off of a previously asked question: Pass by reference multidimensional array with known size

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

I have been trying to figure out how to get my functions to play nicely with 2d array references. A simplified version of my code is:

    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类型**通过引用这样我就可以在一个函数分配给阵列的空间,在另一个设定的值。

I don't know how I can re-write this function so that it will work where I pass bmparray in as an empty unsigned int ** by reference so that I could allocate the space for the array in one function, and set the values in another.

推荐答案

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

Use a class to wrap it, then pass objects by reference

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
};

这篇关于C ++按引用传递动态地分配二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆