2012-03-28

c++ and dynamicly allocated multidimensional arrays

Fancy title huh? Well it sound worse than it is...
suppose we got this:
int myarray[2][4];
Works great right?
But what if we don't know the size when we write the code?
int **myarray = malloc(rows*cols*sizeof(int));
That would be the approach of a C-programmer. So in C++ we got new and don't need malloc, so how about this:
int **myarray = new int[rows][cols];
Well, that doesn't work. In theory we would have to to write new int*[rows] then loop throug all the pointers we just created and assign new int[cols].
Thats a lot of work and possibly a lot of processing depending on how big our array should be.
So my suggestion is to calculate the index ourselves, something the internals of the language would have to do anyways, so we don't waste any processing time there:
int *myarray = new int[rows*cols];
and
myarray[row][col]
becomes
myarray[row*cols + col]
It's just a simple trick that saves a lot of work. And if this becomes more work that than writing the initial loop, one can always write a function for calculating the index or even write an own array class and overwrite the [] operator.

No comments:

Post a Comment