Reputation: 1
I'm trying to create a library including some functions like create a matrix, do add, sub, transpose and invert matrix, and I need to use double pointer In the beginning, I write this code to assign matrix but it seems does not work and I don't know where is the problem
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
static double P[4][4]={ { 1, 0, 0, 0},
{ 0, 1, 0, 0},
{ 0, 0, 1, 0},
{ 0, 0, 0, 1}
};
double **P_M;
void show_matrix(int n,int m,double **matrix)
{
int i,j;
printf("\n The matrix is:\n");
for (i=0;i<n;i++)
{
for (j=0;j<m;j++);
printf(" \t",&matrix[i][j]);
printf("\n");
}
}
double matrix( int n, int m, double **matrix)
{
int row;
/* allocate N 'rows'. */
matrix = malloc( sizeof( double* ) * n );
/* for each row, allocate M actual doubles. */
for( row = 0; row < n; row++ )
matrix[ row ] = malloc( sizeof( double ) * m );
}
void main()
{
int i, j;
matrix(4,4,P_M);
for(i=1; i<5; i++)
for(j=1; j<5; j++)
P_M[i][j] = P[i-1][j-1];
//show_matrix(4,4,P_M);
}
Upvotes: 0
Views: 97
Reputation: 67476
Many problems.
printf(" \t",&matrix[i][j]);
-> printf("%lf \t",matrix[i][j]);
double matrix( int n, int m, double **matrix)
-> double **matrix( int n, int m, double ***matrix)
and the appropriate changes inside the function + return *martix;
at the end if you need it. Otherwise make it void. Call it matrix(4,4,&P_M);
And probably more which I have not noticed. *** pointers are silly and passing the address to the pointer is not necessary.
double **matrix(int n, int m)
{
int row;
double **array;
/* allocate N 'rows'. */
if (!(array = malloc(sizeof(double*) * n)))
{
return NULL;
}
/* for each row, allocate M actual doubles. */
for (row = 0; row < n; row++)
if (!(array[row] = malloc(sizeof(double) * m)))
{
//do something if malloc failed - for example free already allocated space.
return NULL;
}
return array;
}
and in the main
P_M = matrix(4,4);
Upvotes: 2