new创建2维数组出错
我对new创建2维数组不熟悉;用了两次都出错 可能是指针越界问题 但不知道怎么弄 下面是一个 求蛇形填数的代码 麻烦看下出错在哪里 ② 蛇形填数 ③ 回转填数
┌─┬─┬─┬─┬─┐ ┌─┬─┬─┬─┬─┐ ┌─┬─┬─┬─┬─┐
│25│24│23│22│21│ │ 1│ 3│ 4│10│11│ │ 1│16│15│14│13│
├─┼─┼─┼─┼─┤ ├─┼─┼─┼─┼─┤ ├─┼─┼─┼─┼─┤
│20│19│18│17│16│ │ 2│ 5│ 9│12│19│ │ 2│17│24│23│12│
├─┼─┼─┼─┼─┤ ├─┼─┼─┼─┼─┤ ├─┼─┼─┼─┼─┤
│15│14│13│12│11│ │ 6│ 8│13│18│20│ │ 3│18│25│22│11│
├─┼─┼─┼─┼─┤ ├─┼─┼─┼─┼─┤ ├─┼─┼─┼─┼─┤
│10│ 9│ 8│ 7│ 6│ │ 7│14│17│21│24│ │ 4│19│20│21│10│
├─┼─┼─┼─┼─┤ ├─┼─┼─┼─┼─┤ ├─┼─┼─┼─┼─┤
│ 5│ 4│ 3│ 2│ 1│ │15│16│22│23│25│ │ 5│ 6│ 7│ 8│ 9│
└─┴─┴─┴─┴─┘ └─┴─┴─┴─┴─┘
第2个就是蛇形填数的样子
#include <iostream>
using namespace std;
int main()
{
int n;
int b=1,c=1,k = 1;
cout<<"Please enter the range you want:";
cin>>n;
int **a = new int*[n+1];
for(int q = 0;q <= n;q++)
{
a[q] = new int [n+1];
}
for(int w = 1;w <= 2*n-1;w++)
{
if( (b == c)&(c == 1) )
{
a[b][c] = k;
b++;
k++;
}
while( (b - 1>=1)&&(c+1 <=n) )
{
b--;
c++;
a[b][c] = k;
k++;
}
while( (b+1 <=n)&&(c - 1>=1) )
{
b++;
c--;
a[b][c] = k;
k++;
}
if(w%2 == 1)
{
b++;
a[b][c] = k;
k++;
}
else
{
c++;
a[b][c] = k;
k++;
}
}
for(int x = 1; x <=n ;x++)
{
for(int y = 1; y <=n; y++)
{
cout<<a[x][y]<<" ";
}
cout<<endl;
}
for(int q = 0 ; q <=n;q++)
delete []a[q];
delete []a;
}
谢谢了
[解决办法]
要么用vector<vector<int>> ,要么用静态数组, 要么用 : new [m][n];
你这种用法就是没事找事..
[解决办法]
因为越界访问了。所以出错。a[b][c] = k;这样的式子之前你都没判断b和c的值是否会导致越界。所以出错。
[解决办法]
还是用静态数组吧 。。。参考下人家是怎么做的。
#include<stdio.h>#include<string.h>#define MAXN 10int a[MAXN][MAXN];int main(){ int n, x, y, tot = 0; scanf("%d",&n); memset(a,0,sizeof(a)); x = 0; y = n-1; a[x][y] = 1; tot = 1; while(tot < n*n) { while(y+1 < n && a[x][y+1] == 0) { a[x][++y] = ++tot; } while(x+1 < n && a[x+1][y] == 0) { a[++x][y] = ++tot; } while(y-1 >= 0 && a[x][y-1] == 0) { a[x][--y] = ++tot; } while(x-1 >= 0 && a[x-1][y] == 0) { a[--x][y] = ++tot; } } for(x = 0; x < n; x++) { for(y = 0; y < n; y++) printf("%3d",a[x][y]); printf("\n"); } return 0;}