使用动态内存求解任意矩阵的乘法

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
void input(float **p, int x, int y)
{
	for (int i = 0; i < x; i++)
	{
		for (int j = 0; j < y; j++)
		{
			scanf("%f", &p[i][j]);
		}
	}
}
void output(float **p, int x,int y)
{
	for (int i = 0; i < x; i++)
	{
		for (int j = 0; j < y; j++)
		{
			printf("%f   ",p[i][j]);
		}
		printf("\n");
	}
}
void arr_mul(float **p3, float **p1, float **p2, int x, int n,int y)
{
	for (int k = 0; k < x; k++)
	{
		for (int h = 0; h < n; h++)
		{
			for (int j = 0; j < y; j++)
			{
				p3[k][h] += p1[k][j] * p2[j][h];
			}
			printf("%-f   ", p3[k][h]);
		}
		printf("\n");
	}
}
void my_if_NULL(float **p)
{
	if (p == NULL)
	{
		printf("out for memory\n");
		exit(1);
	}
}
void my_free(float**p,int x)
{
	for (int i = 0; i < x; i++)
	{
		free(p[i]);
		p[i] = NULL;
	}
}
int main()
{
	int x, y, m, n;
	float **p1;
	float **p2;
	float **p3;
	printf("arr1[x][y],x=?,y=?\n");
	scanf("%d%d", &x, &y);
    printf("arr2[m][n],m=? , n=?\n");
	scanf("%d%d", &m, &n);
	assert(m == y);
   p1= (float **)calloc(x, 4);
	my_if_NULL(p1);
	for (int i = 0; i < x; i++)
	{
		p1[i] = (float *)calloc(y, 4);
		my_if_NULL(&p1[i]);
	}
	p2 = (float **)calloc(m, 4);
	my_if_NULL(p2);
	for (int i = 0; i < m; i++)
	{
		p2[i] = (float *)calloc(n, 4);
		my_if_NULL(&p2[i]);
	}
	p3 = (float **)calloc(x, 4);
	my_if_NULL(p3);
	for (int i = 0; i < x; i++)
	{
		p3[i] = (float *)calloc(n, 4);
		my_if_NULL(&p3[i]);
	}
	printf("arr1[x][y]:input_ _\n");
	input(p1, x, y);
	printf("arr2[m][n]:input_ _\n");
	input(p2, m, n);
	printf("output:arr1[x][y]\n");
	output(p1,x,y);
	printf("output:arr2[m][n]\n");
	output(p2, m, n);
	printf("arr[x][n]=arr1[x][y]*arr2[m][n]\n");
	arr_mul(p3, p1, p2, x, n,y);
	my_free(p1 ,x);
	my_free(p2, m);
	my_free(p3, x);
	free(p1);
	free(p2);
	free(p3);
	system("pause");
	return 0;
}



posted @ 2016-03-18 00:40  午饭要阳光  阅读(347)  评论(0编辑  收藏  举报