I’d like to use the following function to return a transposed pointer to a multidimensional array.
Code
float** Matrix3f::Transpose( void )
{
float matrix[MATRIX3_DIMS][MATRIX3_DIMS] =
{
{ mMatrix[ 0 ][ 0 ], mMatrix[ 1 ][ 0 ], mMatrix[ 2 ][ 0 ] },
{ mMatrix[ 0 ][ 1 ], mMatrix[ 1 ][ 1 ], mMatrix[ 2 ][ 1 ] },
{ mMatrix[ 0 ][ 2 ], mMatrix[ 1 ][ 2 ], mMatrix[ 2 ][ 2 ] }
};
float** ret = new float*[ MATRIX3_DIMS ];
for ( int i = 0; i < MATRIX3_DIMS; i++ )
{
for ( int j = 0; j < MATRIX3_DIMS; j++ )
{
( *ret )[ i ][ j ] = matrix[ i ][ j ];
}
}
return ret;
}
Description
As shown, I declare a multidimensional array using initialization syntax(using the class-member matrix – mMatrix – to create a transposed version of the matrix itself. I then assign a multidimensional pointer to an array (ret) and loop through, assigning each member of the local array – matrix – to the ret pointer array.
The error I receive is the following:
error: invalid types ‘float[int]’ for array subscript
Question
What exactly am I doing wrong, and how can I accomplish this task?
ret is a pointer to pointer to float. When you dereference it, like this:
(*ret), you get a pointer to float. When you take an index on that, like this:( *ret )[ i ], that gives you a float. When you take an index on that, like this:( *ret )[ i ][ j ], well, you’re trying to index off of a float. That’s not legal.Putting my disgust for this style of coding aside, the first thing you’re doing wrong is you are not allocating the sub-arrays. The compiler error though, refers to the error I illustrated in the first paragraph. Just remove the dereferencing of ret to fix that. You end up with this:
This is totally not exception safe though, and you should be using a class that properly manages memory in an exception safe way, like
std::vector.