70,037
社区成员
发帖
与我相关
我的任务
分享

至少得是调用了 startdirtion()之后。
如果还发生值莫名其妙被改变,请参考下面:
#include <time.h>
#include <stdlib.h>
#include <windows.h>
int main() {
int a,b[11];//本来是b[10],为判断哪句越界,故意声明为b[11]
srand((unsigned int)time(NULL));//按两次F11,等黄色右箭头指向本行时,调试、新建断点、新建数据断点,地址:&b[10],字节计数:4,确定。
while (1) {//按F5,会停在下面某句,此时a的值为10,b[10]已经被修改为对应0..4之一。
b[(a=rand()%11)]=0;
Sleep(100);
b[(a=rand()%11)]=1;
Sleep(100);
b[(a=rand()%11)]=2;
Sleep(100);
b[(a=rand()%11)]=3;
Sleep(100);
b[(a=rand()%11)]=4;
Sleep(100);
}
return 0;
}
全局变量被显式赋值之前就应该是0来着。
您回避了这个关键点,就是上述图片是调试到哪个位置时的状态。
这是所有的代码。求教。
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#include<Windows.h>
#define M 20//迷宫长度
#define N 20//迷宫宽度
int maze[M][N] = {0};
typedef struct//角色可行驶方向
{
int incX;
int incY;
}Direction;
Direction direction[4];
typedef struct Box//角色当前位置与当前方向
{
int dirction_x, dirction_y;
int dir;
struct Box* next;
}BOX,*PBOX;
typedef struct Stack
{
PBOX pTop;
PBOX pBttom;
}STACK,*PSTACK;
void init(PSTACK S)//创建头节点
{
S->pTop = (PBOX)malloc(sizeof(BOX));
if (S->pTop == NULL)
{
printf("内存分配失败");
exit(-1);
}
S->pBttom = S->pTop;
S->pTop->next = NULL;
}
void Push(PSTACK S,PBOX b)
{
PBOX bNew = (PBOX)malloc(sizeof(BOX));
if (bNew)
{
bNew->dirction_x = b->dirction_x;
bNew->dirction_y = b->dirction_y;
bNew->dir = b->dir;
bNew->next = S->pTop;
S->pTop = bNew;
}
}
void Pop(PSTACK S,PBOX b)
{
if (S->pTop == S->pBttom)return;
b->dirction_x = S->pTop->dirction_x;
b->dirction_y = S->pTop->dirction_y;
b->dir = S->pTop->dir;
PBOX L = S->pTop;
S->pTop = L->next;
free(L);
L = NULL;
}
void startdirtion()//填充行走方向
{
direction[0].incX = 1; direction[0].incY = 0;
direction[1].incX = 0; direction[1].incY = 1;
direction[2].incX = -1; direction[2].incY = 0;
direction[3].incX = 0; direction[3].incY = -1;
}
void print(int maze[M][N])//输出画面
{
for (int j = 0; j < N; j++)
{
for (int i = 0; i < M; i++)
{
if (maze[i][j] == 9)printf("@");
if (maze[i][j] == 1)printf("#");
if (maze[i][j] == 0)printf(" ");
}
printf("\n");
}
}
bool findpath(int maze[M][N],Direction direction[],PSTACK S)//判断是否有路可走
{
BOX temp;
int x, y, di;
int line, col;
maze[1][1] = -1;
temp = { 1,1,-1 };
Push(S,&temp);
while (S->pTop != S->pBttom)
{
Pop(S,&temp);
x = temp.dirction_x; y = temp.dirction_y; di = temp.dir + 1;
while (di < 4)
{
system("pause");
//system("cls");
line = x + direction[di].incX;
col = y + direction[di].incY;
if (maze[line][col] == 0)
{
temp = { x,y,di };
Push(S, &temp);
maze[x][y] = 9;
print(maze);
maze[x][y] = 0;
x = line; y = col; maze[line][col] = -1;
if (x == M && y == N)return true;
else di = 0;
}
else di++;
}
}
return false;
}
void startmaze()//初始化迷宫
{
for (int i = 0; i < M; i++)//给迷宫上下两行的墙赋值
{
maze[i][0] = 1;
maze[i][N-1] = 1;
}
for (int i = 0; i < N; i++)//给左右赋值
{
maze[0][i] = 1;
maze[M-1][i] = 1;
}
}
void startdate()//数据集中初始化
{
startdirtion();
startmaze();
}
int main()
{
STACK S;
init(&S);
startdate();
//print(maze);
findpath(maze, &direction[4], &S);
char text = getchar();
}