That would be okay if you were to read or modify the positions of the matrix, however you are going to modify the matrix itself. In your example, you’ll need to create another matrix.
EDITED: I’ve modified this to use unique_ptr, because of the comments (though I don’t think the OP is really ready for/interested on this).
EDITED I know you can transpose the matrix “in-place”. That was not the question from OP, however. Thanks to all commenters about this.
std::unique_ptr<>
is a class the lets you manage a pointer, assuring you that the pointer will be automatically deleted after using it. An option would be auto_ptr
. Unfortunately, it it does not support vectors of arrays. unique_ptr
does support them, though it is part of the new standard c++-0x.
So, you need to modify the formal parameter of transpose to:
void transpose(std::unique_ptr<float**> &array, int rows, int columns)
{
std::unique_ptr<float **> aux = array;
array.reset( new float[columns][rows] );
// now transpose aux into array
}
This also means that you cannot create the original array as you did:
float array[5][4];
This is a matrix on the stack, and you cannot expect to modify the pointer itself, it does not make sense. Better if you do:
int main()
{
std::unique_ptr<float **>array( new float[5][4] );
transpose( array, 5, 4 );
// ... use array ...
}
That said, another solution is to slightly change the signature of the transpose procedure, and make it a function.
std::unique_ptr<float **> transpose(float** array, int rows, int columns)
{
std::unique_ptr<float **> toret( new float[columns][rows] );
// now transpose array into toret
// end
return toret;
}
.. and you would not need to change anything else in your program.
int main()
{
float array[5][4];
std::unique_ptr<float **> transposed( transpose( array, 5, 4 ) );
// ... more things ...
}
2
solved pass two dimensional array to a method C++ [duplicate]