C Language Question Dynamic Memory Allocation Revisit the ma

C Language Question:

Dynamic Memory Allocation

Revisit the matrix addition function. Write the program so that it would not need to take a third pointer for the result matrix. Instead, have the function return a pointer to the results matrix. Provide space for the results matrix inside of the function through dynamic memory allocation.

Solution

#include <stdio.h>

main(){

//create matrix pointers
int *mat1=0, *mat2=0, *mat3, i,j;
int rows=3,cols=3;
int *add(int *mat1, int *mat2, int rows, int cols);
printf(\"\ valus for matrix1:\");
//accept values for matrix 1
mat1 =(int*) malloc(sizeof(int)*rows*cols);
for (i=0;i<rows ;i++ )
{
   for(j=0;j<cols;j++){
   scanf(\"%d\",mat1+i*cols+j);
   }
}
printf(\"\ values for matrxi2\");
//accept valus for matrix2
mat2 =(int*) malloc(sizeof(int)*rows*cols);
for (i=0;i<rows ;i++ )
{
   for(j=0;j<cols;j++){
   scanf(\"%d\",mat2+i*cols+j);
   }
}

mat3=(int*) malloc(sizeof(int)*rows*cols);
    mat3=add(mat1,mat2,rows,cols);
    printf(\"addition of two matrices\");
    for(i=0;i<rows;i++)
    {
        for(j=0;j<cols;j++)
        {
            printf(\"%d \",*(mat3+i*cols+j));
        }
    }

}
int * add(int *mat1,int *mat2,int rows,int cols)
{
    int *mat3=(int*) malloc(sizeof(int)*rows*cols);
    int i,j,k,a1;
    for(i=0;i<rows;i++)
    {
        for(j=0;j<cols;j++)
        {
            a1=*(mat1+i*cols+j)+*(mat2+i*cols+j);
            *(mat3+i*cols+j)=a1;
        }
    }
    return mat3;
}

C Language Question: Dynamic Memory Allocation Revisit the matrix addition function. Write the program so that it would not need to take a third pointer for the
C Language Question: Dynamic Memory Allocation Revisit the matrix addition function. Write the program so that it would not need to take a third pointer for the

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site