Returning Two Dimensional Array from a Function in C

Many authors do not include topics about returning an array from a function in their books or articles. It is because, in most of the cases, there is no need of array to be returned from a function. Since, on passing the array by its name, the address of its first member is passed and any changes made on its formal arguments reflects on actual arguments.

But sometimes, there may arise the situation, where an array has to be returned from a function, for example, multiplying two matrices and assigning the result to another matrix. This can be done by creating a two-dimensional array inside a function, allocating a memory and returning that array. The important thing is you need to FREE the matrix that was allocated.

The source code of returning a two-dimensional array with reference to matrix addition is given here.

#include 
#include 

int **matrix_sum(int matrix1[][3], int matrix2[][3]){
    int i, j;
    int **matrix3;
    matrix3 = malloc(sizeof(int*) * 3);
    
    for(i = 0; i 
 

Or you can use a structure that has a two-dimensional array as a member. Create an instance of structure inside the function and return it.  The code for this approach is given below.

#include 
#include 

typedef struct {
 int m[3][3];
} arr2d;

arr2d matrix_sum(int matrix1[][3], int matrix2[][3]){
    int i, j;
    arr2d result;

    for(i = 0; i