0

Im trying to create 2d array and want to return it tn the function... Any suggestions... I have gone through all the sites and found nothing..

double ** function() {

    double array[] [] ;
                /*code.............. */
    return array:
    ;
    }
  • Why not using a `std::vector>` ? – woz Apr 19 '19 at 20:54
  • 6
    Possible duplicate of [Return a 2d array from a function](https://stackoverflow.com/questions/8617683/return-a-2d-array-from-a-function). Main point is that you have to dynamically allocate to return a raw array, but it is easier to use a vector or similar. – iz_ Apr 19 '19 at 20:57
  • I have used vector only.. But specifically they mentioned to use array... – Mainuddin Shaik Apr 19 '19 at 21:37
  • That's not possible in a reasonable way. The closest thing is to have your caller provide the array unless you want to dynamically allocate it and trust that the caller will remember to free the memory. – eesiraed Apr 20 '19 at 00:19

1 Answers1

1

It's better to use a vector like woz suggested in the comment. But with array you can do this. But first you need to be sure who create the array and it should be that same file/class that delete it. A safe way would be to dont expose the original array and get access to it by using a function (be aware that this code is not thread safe).

class Array2D
{    
public:

    Array2D(int xSize, int ySize)
    {
        xS = xSize;
        yS = ySize;
        arr = new double*[xSize];
        for(int i = 0; i < xSize; ++i)
            arr[i] = new double[ySize];
    }

    bool GetData(int x, int y, double& value)
    {
        if(x < xS && y < yS)
        {
            value = arr[x][y];
            return true;
        }
        return false;
    }

    bool SetData(int x, int y, double value)
    {
        if(x < xS && y < yS)
        {
            arr[x][y] = value;
            return true;
        }
        return false;
    }

    ~Array2D()
    {
        for (int i = 0; i < xS; i++)
        {
            delete [] arr[i];
        }
        delete [] arr;
    }

private:
    //A default constructor here will prevent user to create a no initialized array
    Array2D(){};
    double** arr;
    int xS;
    int yS;
};
white_wolf
  • 51
  • 4