问题遇到的现象和发生背景
矩阵运算:线性代数中的矩阵可以用C语言中的二维数组来表示,编写下列函数实现5*5矩阵的运算。(提示:为了简化编程,不用考虑动态创建二维数组,以指针形式传入即可)。
(1)函数MatrixGenerate(利用srand函数和Rand函数生成一个随机矩阵);
(2)MatrixShow(以二维数组的形式显示矩阵);
(3)MatrixAdd(矩阵的加法);
(4)MatrixSub(矩阵的减法);
(5)MatrixMultiple(矩阵的乘法);
(6)MatrixTran(矩阵的转置);
(7)MatrixMultiple2(矩阵的数乘);
编制生成随机矩阵及矩阵相加的函数,但是运行不出来,一直报错,检查后又没发现什么错误
问题相关代码,请勿粘贴截图
#include<stdio.h>
#include<math.h>
#define max 5
int ShowMatrixEx(int ** a,int m,int n)//以二维数组形式显示矩阵 。
{
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%4d",a[i][j]);
}
printf("\n");
}
}
int ** GenerateRandoMatrix(int m,int n)//生成随机矩阵 。
{
int ** result=(int**)malloc(msizeof(int));
int i;
for(i=0;i<m;i++)
{
result[i]=(int*)malloc(sizeof(int)*n);
}
int j=0;
strabd(time(NULL));
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
result[i][j]=rand()%10;
}
}
return result;
}
int ** MatrixAdd(int ** a,int ** b,int m,int n)//矩阵相加
{
int ** result=(int **)malloc(m*sizeof(int ));
int i,j;
for(i=0;i<m;i++)
{
result[i]=(int)malloc(sizeof(int)*n);
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
result[i][j]=a[i][j]+b[i][j];
}
}
return result;
}
int main()
{
int **a=GenerateRandomMatrix(max,max);
int **b=GenerateRandomMatrix(max,max);
ShowMatrixEx(a,max,max);
ShowMatrixEx(b,max,max);
int i,result;
for(i=0;i<max;i++)
{
free(a[i]);
free(b[i]);
free(result[i]);
}
free(a);
free(b);
free(result);
return 0;
}
运行结果及报错内容
18 24 D:\C语言实践\矩阵运算.c [Warning] incompatible implicit declaration of built-in function 'malloc' [enabled by default]
38 24 D:\C语言实践\矩阵运算.c [Warning] incompatible implicit declaration of built-in function 'malloc' [enabled by default]
55 10 D:\C语言实践\矩阵运算.c [Warning] initialization makes pointer from integer without a cast [enabled by default]
56 10 D:\C语言实践\矩阵运算.c [Warning] initialization makes pointer from integer without a cast [enabled by default]
62 3 D:\C语言实践\矩阵运算.c [Warning] incompatible implicit declaration of built-in function 'free' [enabled by default]
66 2 D:\C语言实践\矩阵运算.c [Warning] incompatible implicit declaration of built-in function 'free' [enabled by default]
68 2 D:\C语言实践\矩阵运算.c [Warning] passing argument 1 of 'free' makes pointer from integer without a cast [enabled by default]
64 14 D:\C语言实践\矩阵运算.c [Error] subscripted value is neither array nor pointer nor vector
68 2 D:\C语言实践\矩阵运算.c [Warning] passing argument 1 of 'free' makes pointer from integer without a cast [enabled by default]
我的解答思路和尝试过的方法
尝试过确定result数组的变量值
我想要达到的结果
函数成功编制可以运行。
可以实现生成随机数组并实现矩阵相加。