Saturday, August 27, 2011

Returning Two Dimensional Array from a Function in C

Many author do not include topics about returning array from a functions 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 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 have 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 pointer to an array. The source code of returning two dimensional array with reference to matrix addition is given here.

#include <stdio.h>
int (*(Matrix_sum)(int matrix1[][3], int matrix2[][3]))[3]{
    int i, j;
    for(i = 0; i < 3; i++){
        for(j = 0; j < 3; j++){
            matrix1[i][j] = matrix1[i][j] + matrix2[i][j];
        }
    }
    return matrix1;
}
int main(){
    int x[3][3], y[3][3];
    int (*a)[3]; //pointer to an array
    int i,j;
    printf("Enter the matrix1: \n");
    for(i = 0; i < 3; i++){
        for(j = 0; j < 3; j++){
            scanf("%d",&x[i][j]);
        }
    }
    printf("Enter the matrix2: \n");
    for(i = 0; i < 3; i++){
        for(j = 0; j < 3; j++){
            scanf("%d",&y[i][j]);
        }
    }
    a = Matrix_sum(x,y); //asigning
    printf("The sum of the matrix is: \n");
    for(i = 0; i < 3; i++){
        for(j = 0; j < 3; j++){
            printf("%d",a[i][j]);
            printf("\t");
        }
        printf("\n");
    }
    return 0;
}

6 comments: