Dominic Dalessandro
Dominic Dalessandro

Reputation: 13

How to return a 2D array from a C function?

So I have to write a program that sorts a 2d array and then returns it but I just found out you cant return an array from a function. I tried researching this but nothing fixes the problem. Any help is appreciated, thanks.

Below is the function I wrote to sort the vertical rows.

int vertSort(int matrix[][51], int size)
{
    for(c=0;c<size;c++)
    {

        for(r=0;r<size-1;r++)
        {
            if(matrix[c][r]>matrix[c][r+1])
            {
                printf("Swap row %d column %d with row %d column %d", r, c, r, c)
                int tmp=matrix[c][r];
                matrix[c][r]=matrix[c][r+1];
                matrix[c][r+1]=tmp;


            }

        }
    }
    return matrix;


}

Upvotes: 1

Views: 164

Answers (3)

user3386109
user3386109

Reputation: 34849

The correct syntax is impossibly messy, so I suggest using a typedef as shown below

typedef int (*ptr51)[51];

ptr51 vertSort( int matrix[][51], int size )
{
    matrix[0][2] = 99;
    matrix[1][1] = 88;
    return( matrix );
}

int main( void )
{
    int test[2][51] = { { 10, 20, 30 }, { 40, 50, 60 } };

    ptr51 output = vertSort( test, 0 );

    for ( int row = 0; row < 2; row++ )
    {
        for ( int col = 0; col < 3; col++ )
            printf( "%d ", output[row][col] );
        printf( "\n" );
    }
}

Here is the impossibly messy syntax without a typedef

int (*(vertSort( int matrix[][51], int size )))[51]
{
    matrix[0][10] = 99;
    matrix[1][50] = 88;
    return( matrix );
}

int main( void )
{
    int test[2][51] = { { 10, 20, 30 }, { 40, 50, 60 } };

    int (*output)[51] = vertSort( test, 0 );

    for ( int row = 0; row < 2; row++ )
    {
        for ( int col = 0; col < 51; col++ )
            printf( "%d ", output[row][col] );
        printf( "\n" );
    }
}

Upvotes: 0

M.M
M.M

Reputation: 141613

Your code does not need to return anything, it modifies the caller's copy of the array. (Arrays cannot be passed by value in C). Change the int return type to void and all will be well.

Upvotes: 3

doptimusprime
doptimusprime

Reputation: 9411

function's return type should be int ** and typecast matrix to int **. It should work for you.

int** vertSort(int matrix[][51], int size)
{
     for(c=0;c<size;c++)
     {

        for(r=0;r<size-1;r++)
        {
             if(matrix[c][r]>matrix[c][r+1])
             {
                printf("Swap row %d column %d with row %d column %d", r, c, r, c)
                int tmp=matrix[c][r];
                matrix[c][r]=matrix[c][r+1];
                matrix[c][r+1]=tmp;


              }

         }
    }
    return (int **)matrix;


}

Upvotes: -1

Related Questions