Powered By Blogger

Thursday 28 April 2011

Create a 2D array dynamically in called function then editing its value and then it's passed to main() using double pointer. Finally updated matrix is printed from main().

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<math.h>
int ** passed(int,int);
int main(void)
{
    int **vam,i=0,j=0,order[2];
    printf("\n**************** Addition to matrix by passing pointer ****************\n\n");
   
    printf("Input the order of the matrix (m n) ::\n");
    for(i=0;i<2;i++)
        scanf(" %d",&order[i]);
    //Function called to get the input and to edit
    vam=passed(order[0],order[1]);
    //Matrix edited and is stored into vam
    printf("\n\nMatrix after ::\n\n");


    for(i=0;i<order[0];i++)
    {
        for(j=0;j<order[1];j++)
        {
            printf("%5d",vam[i][j]);
        }
        printf("\n");
    }
    getch();
    return 0;
}

int ** passed(int row,int col)
{
    int **matrix,i=0,j=0,val=0;
    matrix=(int**)malloc((row+2)*sizeof(int*));
    for(i=0;i<row;i++)
        matrix[i]=(int*)malloc((col+2)*sizeof(int));
    printf("\n\nEnter the elements of the matrix (Row Wise)::\n");
    for(i=0;i<row;i++)
        for(j=0;j<col;j++)
            scanf("%d",&matrix[i][j]);
    printf("\n\nMatrix Before ::\n\n");
    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            printf("%5d",matrix[i][j]);
        }
        printf("\n");
    }

    //updating matrix    printf("\n\nEnter a value to add to each element of the matrix:: ");
    scanf("%d",&val);
    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            matrix[i][j]+=val;
        }
    }
    //returning double pointer to the main();
    return matrix;
}

2 comments: