- 论坛徽章:
- 0
|
问题描述:本来想写一个打印矩阵的程序,由于一时疏忽,标红那处代码申请内存时写错了,本来应该申请n*n,但写成了n,于是就出现了很诡异的现象——如果我输入的矩阵宽度为2或3时,就会程序最后释放内存时出错;而3以上就没问题。没想明白原因,还望高人指明啊。。。
#include <iostream>
#include <cerrno>
int main()
{
using namespace std;
int n = 0;
int m = 1;
int max;
int row = 0;
int max_row;
int column = 0;
int max_column;
int i = 0;
int j = 0;
int *ptr;
cout << "Please input the width of the matrix...\n";
cin >> n;
// Check of the incoming value
if (n < 2)
{
cout << "The width of the matrix can't less than 2!\n";
return -1;
}
// Init of varibles
max = n*n;
max_row = n-1;
max_column = n-1;
ptr = new int [n];
if (NULL == ptr)
{
perror("malloc()...");
return -2;
}
// The end of loop is m = max
for (; m < max; )
{
// up loop
for (i = column; i < max_column; i++)
{
cout << n*row+i << endl;
*(ptr+n*row+i) = m;
m++;
}
// right loop
for (i = row; i < max_row; i++)
{
cout << n*i+max_column << endl;
*(ptr+n*i+max_column) = m;
m++;
}
// down loop
for (i = max_column; i > column; i--)
{
cout << n*max_row+i << endl;
*(ptr+n*max_row+i) = m;
m++;
}
// left loop
for (i = max_row; i > row; i--)
{
cout << n*i+column << endl;
*(ptr+n*i+column) = m;
m++;
}
row++;
column++;
max_row--;
max_column--;
if (row >= max_row)
{
if (n % 2)
{
*(ptr+n*row+column) = m;
}
break;
}
}
// printf the matrix
cout << "The matrix is below:\n";
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
printf("%-4d", *(ptr+n*i+j));
}
cout << endl;
}
// realse resource
delete [] ptr;
return 0;
}
|
|