How to pass arrays by reference in C++ Winforms

José Carlos 886 Reputation points
2023-03-27T19:23:43.92+00:00

Friends,

I have a method to resize a two-dimensional array in C#. I'm trying to transform this method to C++ Winforms.

I've tried several times but I'm not succeeding. Follow the method and method call in C#

At the beginning of the program, I define a matrix with 1 line and 6 columns like string.

I call a method that reads a database and populates a dataset. From there, I call the method passing the array name by reference, the number of rows, and the number of columns.

As record insertions occur, I need to resize the array. At that time I call the method passing the original matrix called todoagenda;

I do this with two more matrices. I call the same method but passing different matrices.

        void ResizeArray<T>(ref T[,] original, int x, int y)
        {
            T[,] newArray = new T[x, y];
            int minX = Math.Min(original.GetLength(0), newArray.GetLength(0));
            int minY = Math.Min(original.GetLength(1), newArray.GetLength(1));

            for (int i = 0; i < minY; ++i)
                Array.Copy(original, i * original.GetLength(0), newArray, i * newArray.GetLength(0), minX);

            original = newArray;
        }

The call is:

ResizeArray<String>(ref todaagenda, TotReg, 7); // resize the array to the new size


Developer technologies C++
Developer technologies Visual Studio Other
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2023-03-27T20:09:06.96+00:00

    Try this:

    generic<typename T>
    void ResizeArray( array<T, 2>^% original, int x, int y )
    {
        array<T, 2>^ newArray = gcnew array<T, 2>( x, y );
    
        int minX = Math::Min( original->GetLength( 0 ), newArray->GetLength( 0 ) );
        int minY = Math::Min( original->GetLength( 1 ), newArray->GetLength( 1 ) );
    
        for( int i = 0; i < minY; ++i )
        {
            Array::Copy( original, i * original->GetLength( 0 ), newArray, i * newArray->GetLength( 0 ), minX );
        }
    
        original = newArray;
    }
    

    Sample usage:

    array<String^, 2>^ matrix1 = . . .
    ResizeArray( matrix1, 10, 3 );
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. José Carlos 886 Reputation points
    2023-03-27T21:18:48.4466667+00:00

    Hi friend Viorel.

    Where do I put the line generic<typename T>.

    I think only that line is missing, because the method is all underlined with error.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.