c - 使用双指针创建函数进行矩阵运算
问题描述
我正在尝试创建一个库,其中包含一些函数,例如创建矩阵、添加、子、转置和反转矩阵,我需要使用双指针在开始时,我编写这段代码来分配矩阵,但它似乎不起作用我不知道问题出在哪里
#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);
推荐阅读
- java - 在Java列表中按多个值过滤和汇总对象
- java - AAR Android 库文件
- android - 无法使用 adb shell for appium 查看 appActivity
- javascript - babel/parser生成ast后,立即使用babel/generator输出,结果不一致
- java - Android Studio 依赖错误
- css - 带有浮动元素和垂直居中动态内容的 div
- python - 网状:AttributeError:模块'importlib'没有属性'util'
- r - 如何使用 BaseR 确定图例的形式?
- python - 数据框字符串列中的字符匹配和替换
- sql - SQL 非重复连接到使用空值作为通配符的表