Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Passing a dynamicly allocated 2D array by reference

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

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

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.

like image 455
Dortz Avatar asked Aug 30 '26 06:08

Dortz


2 Answers

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
};
like image 158
jturcotte Avatar answered Sep 02 '26 05:09

jturcotte


typedef array_type unsigned int **;
initialize_BMP_array(array_type& bmparray, int height, int width)
like image 30
BigSandwich Avatar answered Sep 02 '26 07:09

BigSandwich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!