图像处理C++基础 01 ——指针

目标:

  1. 初步掌握visual studio 2013 中控制台c程序的建立。
  2. 结合课本讲解指针概念;指针上机练习。
  3. 讲解动态分配和释放。 malloc/free.
  4. 一维指针动态分配和释放练习。
  5. 二维指针概念讲解。二维指针动态分配和释放练习。


作业:

矩阵乘法

  1. 用户输入矩阵1行数、列数,然后提示用户输入各元素;
  2. 用户输入矩阵2行数、列数,然后提示用户输入各元素;
  3. 输入后计算相乘结果矩阵。


要求:

  1. 自己安装Visual studio 2013. 从微软官网上下载visual studio 2013 (Community edition),然后申请序列号(免费),安装。
  2. 建立控制台应用程序。(上网查怎么建立)
  3. 使用二维指针及动态分配,完成作业。 (参考:数值算法大全,4个美国人写的,第2版或第3版的引言部分)
#include 
    
     
#include 
     
      
#include 
      
       
using namespace std;

int main(void)
{
	int n, m, l;
	int **a = NULL, **b = NULL, **result = NULL;
	int i, j, k;

	cout<<"Please enter the rows and columns of the first matix:";	/*输入矩阵行列数*/
	cin >> n >> m;
	cout<<"Please enter the columns of the second matix:";
	cin >> l;

	if ((a = (int**)malloc(n*sizeof(int*))) == NULL)	/*建立矩阵A*/
	{
		cout << "error!";
		exit(1);
	}
	for (i = 0; i < n; i++)
	{
		if ((a[i] = (int*)malloc(m*sizeof(int))) == NULL)
		{
			cout << "error!";
			exit(1);
		}
	}

	if ((b = (int**)malloc(m*sizeof(int*))) == NULL)	/*建立矩阵B*/
	{
		cout << "error!";
		exit(1);
	}
	for (i = 0; i < m; i++)
	{
		if ((b[i] = (int*)malloc(l*sizeof(int))) == NULL)
		{
			cout << "error!";
			exit(1);
		}
	}

	if ((result = (int**)malloc(m*sizeof(int*))) == NULL)	/*建立矩阵RESULT*/
	{
		cout << "error!";
		exit(1);
	}
	for (i = 0; i < n; i++)
	{
		if ((result[i] = (int*)malloc(l*sizeof(int))) == NULL)
		{
			cout << "error!";
			exit(1);
		}
	}

	cout << "Please enter the elements of the first matix:" << endl;	/*输入AB矩阵的元素*/
	for (i = 0; i < n; i++)
		for (j = 0; j < m; j++)
			cin >> a[i][j];
	cout << "Please enter the elements of the second matix:" << endl;
	for (i = 0; i < m; i++)
		for (j = 0; j < l; j++)
			cin >> b[i][j];

	for (i = 0; i < n; i++)		/*数组RESULT清零*/
		for (j = 0; j < l; j++)
			result[i][j] = 0;
	
	for (i = 0; i < n; i++)
	{
		for (j = 0; j < l; j++)
		{
			for (k = 0; k < m; k++)
				result[i][j] += a[i][k] * b[k][j];
			cout << result[i][j]<<'\t';
		}
		cout << endl;
	}
			
	for (i = 0; i < n; i++)		/*释放空间*/
	{
		free(a[i]);
		free(result[i]);
	}
	free(a);
	a = NULL;
	free(result);
	result = NULL;
	for (i = 0; i < m; i++)
		free(b[i]);
	free(b);
	b = NULL;

	system("pause");
	return 0;
}
      
     
    

猜你喜欢

转载自blog.csdn.net/qq_26751117/article/details/53442885