#include <string>
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int matrixSize;
cout<<"请输入矩阵的大小:"<<endl;
cin>>matrixSize;
if (matrixSize<=0)
{
cout<<"矩阵大小必须大于1"<<endl;
return -1;
}
cout<<"矩阵大小:"<<matrixSize<<endl;
int *pMatrix = (int*)malloc(matrixSize*matrixSize*sizeof(int));
if (!pMatrix)
{
cout<<"内存申请失败!"<<endl;
}
int x_lt = 0, y_lt = 0; //左上顶点
int x_rt = 0,y_rt = matrixSize-1; //右上顶点
int x_rb = matrixSize-1,y_rb = matrixSize-1; //右下顶点
int x_lb = matrixSize-1,y_lb = 0; //左下顶点
int offset = 0;
int value = 1;
int changeValue;
while ( x_lt <= x_rb )
{
if (x_lt == x_rb)
{
*(pMatrix+(y_lt+matrixSize*x_lt)) = value;
break;
}
changeValue = y_lt;
for (int i=0; i<matrixSize-1-offset; ++i)
{
*(pMatrix+(changeValue+matrixSize*x_lt)) = value;
value++;
changeValue++;
}
changeValue = x_rt;
for (int i=0; i<matrixSize-1-offset; ++i)
{
*(pMatrix+(y_rt+matrixSize*changeValue)) = value;
value++;
changeValue++;
}
changeValue = y_rb;
for (int i=0; i<matrixSize-1-offset; ++i)
{
*(pMatrix+(changeValue+matrixSize*x_rb)) = value;
value++;
changeValue--;
}
changeValue = x_lb;
for (int i=0; i<matrixSize-1-offset; ++i)
{
*(pMatrix+(y_lb+matrixSize*changeValue)) = value;
value++;
changeValue--;
}
x_lt++;
y_lt++;
x_rt++;
y_rt--;
x_rb--;
y_rb--;
x_lb--;
y_lb++;
offset+=2;
}
for (int i=0; i<matrixSize*matrixSize; ++i)
{
value = *(pMatrix+i);
cout<<value<<"\t";
if ((i+1)%matrixSize == 0)
{
cout<<endl;
}
}
cout<<endl;
free(pMatrix);
pMatrix = nullptr;
return 0;
}