C++ question

Sorry for posting here, but not getting an answer anywhere else.

My prob is dynamically allocating a 2D array:

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

where ptr is defined as;

float **ptr;

This is not allowed, so what syntax would I use to do this? I want to be able to reference the array using *[j] and not fiddle around with pointer notation.

Unfortunately the only way I know of is a bit ugly…
Try this:

Thing::Thing(int num1, int num2)
{
ptr = new float *[num1];
for (int x = 0; x < num1; x++) ptr = new float[num2];
}

And you’ll need similar code in the destructor to clean up the memory afterward. But this will let you use ptr*[j] type notation, I believe.

I hope this helps.

For this sort of thing I often try searching google groups. Someone’s always asked the same q before, if you can find it. Sorry I can’t be more help.

Or maybe have an array of classes, each of which implements an array?

You can use the Numerical Recipes codes, nrutil.h and nrutil.c, available here. These are public domain, and implement what Garnet described, more-or-less.

As far as I know Garnet’s answer is the simplest. One thing to remember is that the syntax

float **ptr;

creates a pointer to a pointer to a float, whereas what you need is a pointer to an array of pointers to arrays of floats.

If you want a 2D array of objects of type T, you declare it as T** Array. If you want pointers of type T, you declare it as T*** Array.

Garnet’s initialization is the only way I know. Gets to be a bitch when you’ve got more than three or four dimensions.

You know I tried Garnet’s method and I got a segmentation fault, i’d better have a closer look at my code.

As for using a library - hell is other peoples code.