-5

Possible Duplicate:
How do I use arrays in C++?

I am not sure if how to do this in C++:

main()
{
   float array[5][4];   

   transpose(array); 
}

void transpose(float** array);

=> I got some some compilation error: vector<KeypointMatch, std::allocator<KeypointMatch> >

How can I pass the variable of two dimensional array to a method in C++?

Thanks in advance.

Community
  • 1
  • 1
olidev
  • 20,058
  • 51
  • 133
  • 197

1 Answers1

-1

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 ...
}
Baltasarq
  • 12,014
  • 3
  • 38
  • 57
  • 2
    This uses naked pointers to manage resources, and is thus unsafe. If the part labeled 'now transpose aux into array' throws for whatever reason, this leaks. `-1` from me. – sbi Nov 15 '11 at 19:00
  • I'm -1ing as well for the same reason as @sbi *and* because you can actually transpose a matrix in-place. – R. Martinho Fernandes Nov 16 '11 at 02:48