我正在尝试创建一个包含一些函数的库,例如创建矩阵、添加、减去、转置和反转矩阵,我需要使用双指针 一开始,我写了这段代码来分配矩阵,但它似乎不起作用,我不知道问题出在哪里
#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);
}
最佳答案
很多问题。
- 越界 - 因为索引从零开始。
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)
以及函数内部的适当更改 +return *martix;
如果需要,请在最后。否则作废。称它为matrix(4,4,&P_M);
可能还有更多我没有注意到的。 *** 指针很傻,没有必要将地址传递给指针。
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;
}
主要是
P_M = matrix(4,4);
关于c - 使用双指针创建函数进行矩阵运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50315160/