Is this the right way to return a two-dimensional array?

Given the following C-code:

#include <stdio.h>

int mat1[2][4] = {
    {9, 10, 11, 12},
    {13, 14, 15, 16}
};

int (*(transpose)(int matrix[][4]))[2] {
    static int mat[4][2];
    int i;
    int j;

    printf("I am the function transpose()\nand I'm transposing 2x4 matrices.\n\n");
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 4; j++) {
            mat[j][i] = matrix[i][j];
        }
    }
    return mat;
}

int main() {
    int (*mat_transpose)[2];
    int i;
    int j;
    mat_transpose = transpose(mat1);

    for (j = 0; j < 2; j++) {
        for (i = 0; i < 4; i++) {
            printf("mat_transpose[%d][%d] = %d\n", i, j, mat_transpose[i][j]);
        }
    }
    return 0;
}

The function transpose()returns a two-dimensional array (or, rather, a pointer to an array of pointers). Is this the right way to achieve this? Looking at various issues related to Stackoverflow, it seems that there is no standard way to do this, and that is a lot. Is there any standard regarding returning two- or multi-dimensional arrays?

+4
source share
4 answers

Is this a valid way to return a two-dimensional array?

Yes. Returns a pointer to a local variable static. I would suggest that you can typedefreturn a type

typedef matx[2];  

matx *transpose(int matrix[][4])){ /* Function body */ }
+1

,

#include <stdio.h>

void transpose(int rows, int columns,
        int matrix[rows][columns], int mat[columns][rows])
{
    int i;
    int j;

    printf("I am the function transpose()\n");
    printf("And I'm transposing 2x4 matrices.\n\n");
    for (i = 0; i < rows; i++)
    {
        for (j = 0; j < columns; j++)
        {
            mat[j][i] = matrix[i][j];
        }
    }
}

int main()
{
    int mat1[2][4] =
    {
        {9, 10, 11, 12},
        {13, 14, 15, 16}
    };
    int mat_transpose[4][2];
    int i;
    int j;

    transpose(2, 4, mat1, mat_transpose);
    for (j = 0; j < 2; j++)
    {
        for (i = 0; i < 4; i++)
        {
            printf("mat_transpose[%d][%d] = %d\n", i, j, mat_transpose[i][j]);
        }
    }
    return 0;
}

mat1 , .

+3

You must have your function

    int **transpose(int **matrix, int row, int columns)
    {
       int **mat;

       // Malloc you array, copy what you need and return it
       ...
    }

Row and columns is the number of rows and column int **matrix

0
source

This is true because he does what he claims, but I think you already know that.

I don't think there are things like standards for returning n-dimensional arrays, only best practices.

The only thing I can say about your function is that it does not have universality (you process only 2 * 4 matrices), but perhaps this is not your goal.

0
source

All Articles