0

## 緩衝區溢位的問題，為什麼會出現讀取到負數個位元組?

IDE: vs code

#include
#include<conio.h>//非標準函式
#include<Windows.h>//不太了解只懂部分功能
using namespace std;

int a[20][20] = { {1,1,1,1,1,1,1},
{1,8,0,0,0,0,1},
{1,0,0,1,1,1,1},
{1,0,0,0,0,0,1},
{1,1,0,1,0,1,1},
{1,0,0,1,0,0,0},
{1,1,1,1,1,1,1} };

int main() {
int one = 0, two = 0,x=1, y=1,n=0;
char in;
for (one=0; one < 7; one++) {
for (two = 0; two < 7; two++) {
if (a[one][two] != 0) {
cout << a[one][two];
}
else {
cout << " ";
}
}
cout << endl;
}

``````while (1) {

in = _getch();

if (in=='w') {
if (a[x - 1][y] != 1) {
n = a[x][y];
a[x][y] = a[x - 1][y];
a[x - 1][y] = n;
x--;
}
}
else if (in=='s') {
if (a[x + 1][y] != 1) {
n = a[x][y];
a[x][y] = a[x + 1][y];
a[x + 1][y] = n;
x++;
}
}
else if (in == 'd') {
if (a[x][y+1] != 1) {
n = a[x][y];
a[x][y] = a[x][y+1];
a[x][y+1] = n;
y++;
}
}
else if (in == 'a') {
if (a[x][y-1] != 1) {
n = a[x][y];
a[x][y] = a[x][y-1];
a[x][y-1] = n;
y--;
}
}

system("cls");
for (one = 0; one < 7; one++) {
for (two = 0; two < 7; two++) {
if (a[one][two] != 0) {
cout << a[one][two];
}
else {
cout << " ";
}
}
cout << endl;
}
if (x == 5 && y == 6) {
break;
}
}
``````

cout << "You Win!!" << endl;
}

### 1 個回答

2

iT邦大神 1 級 ‧ 2021-03-03 07:48:44

``````if (in=='w') {
if (a[x - 1][y] != 1) {
n = a[x][y];
a[x][y] = a[x - 1][y];
a[x - 1][y] = n;
x--;
}
}
else if (in=='s') {
if (a[x + 1][y] != 1) {
n = a[x][y];
a[x][y] = a[x + 1][y];
a[x + 1][y] = n;
x++;
}
}
else if (in == 'd') {
if (a[x][y+1] != 1) {
n = a[x][y];
a[x][y] = a[x][y+1];
a[x][y+1] = n;
y++;
}
}
else if (in == 'a') {
if (a[x][y-1] != 1) {
n = a[x][y];
a[x][y] = a[x][y-1];
a[x][y-1] = n;
y--;
}
}
``````

``````if (in=='w') {
if ((x-1)>=0) {
if (a[x - 1][y] != 1) {
n = a[x][y];
a[x][y] = a[x - 1][y];
a[x - 1][y] = n;
x--;
}
} else {
//已碰到最「上面」的邊界
}
}
else if (in=='s') {
if ((x+1)<=6) {
if (a[x + 1][y] != 1) {
n = a[x][y];
a[x][y] = a[x + 1][y];
a[x + 1][y] = n;
x++;
}
} else {
//已碰到最「下面」的邊界
}
}
else if (in == 'd') {
if ((y+1)<=6) {
if (a[x][y+1] != 1) {
n = a[x][y];
a[x][y] = a[x][y+1];
a[x][y+1] = n;
y++;
}
} else {
//已碰到最「右邊」的邊界
}
}
else if (in == 'a') {
if ((y-1)>=0) {
if (a[x][y-1] != 1) {
n = a[x][y];
a[x][y] = a[x][y-1];
a[x][y-1] = n;
y--;
}
} else {
//已碰到最「左邊」的邊界
}
}
``````

'''
asdfasdf
'''