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

This question is based on a previously asked question: Pass reference multidimensional array with known size

I am trying to figure out how to make my functions play well with references to a 2d array. A simplified version of my code:

    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 rewrite this function so that it works where I pass bmparray as an empty unsigned int ** by reference so that I can allocate space for the array in one function and set the values ​​in another.

+3
source share
4 answers

Use the class to transfer it, then pass the 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
};
+3
typedef array_type unsigned int **;
initialize_BMP_array(array_type& bmparray, int height, int width)
+3

... , , 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 ( ).

, .

+2

++, , .

void initialize_BMP_array(vector<vector<unsigned int> > &bmparray, int height, int width);
+1

Source: https://habr.com/ru/post/1702938/


All Articles