Link to home
Start Free TrialLog in
Avatar of shayad
shayad

asked on

Dynamic memory allocation

Hi,

This question is not very specific to C++. How can I dynamically allocate memory to a three dimensional or a two dimensional array ?

Allocation of memory is no problem but, keeping track of the offsets into the array is something which will have to be done programatically. Is my conjecture correct ?

Please reply.

Shayad.
Avatar of captainkirk
captainkirk

in C/C++, you could use the realloc() function to dynamically resize the array and repopulate it programmatically. The standard pointer arithmetic applies when you want to reference elements. Arrays are stored in row order in C/C++.


ASKER CERTIFIED SOLUTION
Avatar of chensu
chensu
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Example :

you have array of aai[4][2] of int
The elements of aai[4][2] are stored in memory in the following order.

aai[0][0]aai[0][1]aai[1][0]aai[1][1]
aai[2][0]aai[2][1]aai[3][0]aai[3][1]

*aai is of type int[]. Note that:-

aai[1][2] == *( (aai[1])+2) ==
*(* (aai+1)+2)
and that numerically
   aai == aai[0] == &aai[0][0]

 




You can use chensus approach, allocating arrays of pointers which means you can use the [][] syntax directly.  

An alternative way is to wrap the whole thing in a class, and let that do the work for you,  the class will need to understand offsets etc, but the user won't.

The following code is an example of how you could create a matrix class that shows how the class could manage offsets for you:

#include <iostream>
using namespace std;

class Matrix2D {
public:
    Matrix2D(int xdim, int ydim)
        : mXDim(xdim), mYDim(ydim)
    {
        mData = new double[xdim*ydim];
    }

    virtual ~Matrix2D() { delete [] mData; }

    class Matrix1D
    {
    public:
        friend class Matrix2D;

        double& operator[](size_t j)
        { return mDataPtr[j]; }
        double operator[](size_t j) const
        { return mDataPtr[j]; }
    private:
        Matrix1D(double* pData)
            : mDataPtr(pData) {};

        double* mDataPtr;
    };

    Matrix1D operator[](size_t i)
    { return Matrix1D(&mData[i*mXDim]); }
    const Matrix1D operator[](size_t i) const
    { return Matrix1D(&mData[i*mXDim]); }
private:
    double* mData;
    size_t mXDim;
    size_t mYDim;
};


void main()
{
    Matrix2D m(3,3);

    for (int i=0; i<3; i++)
        for (int j=0; j<3; j++)
            m[i][j] = i*3+j+1;

    for (i=0; i<3; i++)
        for (int j=0; j<3; j++)
            cout << m[i][j] << endl;
}
Avatar of shayad

ASKER

Thanks Chensu !
The examples are very good.