展开全部
这得用到线性函数啊,都快忘没了;
先分析一下矩阵相乘的算法:
a[m][n] * b[n][p] = c[m][p]
其中c[i][j] = a[i][0] * b[0][j] + ... + a[i][n-1] * b[n-1][j]
现在我们就可以来写程序了
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;
#define COLUM_NUM 2
typedef struct array
{
int (*parray)[COLUM_NUM];
int colum; //列
int row; //行
}STRU_ARRAY;
int func(STRU_ARRAY *parray_1, STRU_ARRAY *parray_2, STRU_ARRAY **out_array);
int main(int argc, char **argv)
{
int a[2][COLUM_NUM] = {{1,2}, {3,4}};
int b[2][COLUM_NUM] = {{4,3}, {2,1}};
int *print_tmp = NULL;
STRU_ARRAY local_array1 = {a, 2, 2};// 1 2
// 3 4
STRU_ARRAY local_array2 = {b, 2, 2};// 4 3
// 2 1
STRU_ARRAY *local_out_array = NULL;
#if 0
printf("%d %d %d %d %d %d\n",
local_array1.parray[0][0],
local_array1.parray[0][1],
local_array1.parray[1][0],
local_array1.parray[1][1], local_array1.row, local_array1.row);
printf("%d %d %d %d %d %d\n",
local_array2.parray[0][0],
local_array2.parray[0][1],
local_array2.parray[1][0],
local_array2.parray[1][1], local_array2.row, local_array2.row);
#endif
int result = func(&local_array1, &local_array2, &local_out_array);
print_tmp = (int *)local_out_array->parray;
//printf("%d %d \n", print_tmp[0], print_tmp[1]);
//printf("%d %d \n", print_tmp[2], print_tmp[3]);
cout<<print_tmp[0]<<" "<<print_tmp[1]<<endl;
cout<<print_tmp[2]<<" "<<print_tmp[3]<<endl;
free(local_out_array->parray);
free(local_out_array);
}
int func(STRU_ARRAY *parray_1, STRU_ARRAY *parray_2, STRU_ARRAY **out_array)
{
int i = 0;
int j = 0;
int n = 0;
int *p = NULL;
int (*ptmp)[COLUM_NUM] = NULL;
if ((NULL == parray_1) || (NULL == parray_2))
{
return -1;
}
*out_array = (STRU_ARRAY *)malloc(sizeof(STRU_ARRAY));
if (NULL == *out_array)
{
return -1;
}
memset(*out_array, 0, sizeof(STRU_ARRAY));
(*out_array)->parray = (int (*)[COLUM_NUM])malloc(parray_2->colum * parray_1->row);
if (NULL == (*out_array)->parray)
{
return -1;
}
memset((*out_array)->parray, 0, (parray_2->colum * parray_1->row) * 4);
ptmp = (*out_array)->parray;
//i为新生成矩阵的行,j为新生成矩阵的列
for (i = 0; i < parray_1->row; i++)
{
p = (int *)ptmp;
for (j = 0; j < parray_2->colum; j++)
{
for (n = 0; n < parray_1->colum; n++)
{
p[j] += parray_1->parray[i][n] * parray_2->parray[n][j];
}
}
ptmp++;
}
return 0;
}
1 2
3 4
与
4 3
2 1
相乘
运行结果正确:
./array
8 5
20 13
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询