Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dynamically allocating multidimensional arrays?

Status
Not open for further replies.

DanglingPointer

Programmer
Apr 5, 2003
22
GB
How can I dynamically allocate a 2d array with parameters passed to a constructor?

I want to do this:

Thing::Thing(int num1, int num2)
{
ptr = new float[num1][num2];
}

But this isn't valid syntax. How would I go about this? Overloading the new operator?
 
The easiest, and less efficient way, would be to do this
Code:
Thing::Thing(int row, int col)
{
    ptr = new float*[row];
    
    for (int i = 0; i < row; i++)
        ptr[i] = new float[col];
}
However, this requires row + 1 calls to new. A better way that only calls new twice would be
Code:
Thing::Thing(int row, int col)
{
    data = new float[row * col];
    ptr = new float*[row];
    
    for (int i = 0; i < row; i++)
    {
        ptr[i] = data;
        data += col;
    }
}
It's not as easy to follow, but you allocate one large chunk and then place pointers at set intervals to simulate a matrix. In the code I've given no error checking is done, be sure to do that in your program. :)
 
In multidimensional allocating is possible dynamically change only very first index, the rest indexes must have constant size.

#define num2 10

Thing::Thing(int num1)
{
float (*ptr)[num2];
ptr = new float[num1][num2];

}

If you want more dynamical indexes, follow Akarui's advice.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top