是课本上的一道例题
#include<iostream>
#define M 4
#define N 4
using namespace std;
int mg[M + 2][N + 2] = {
{1,1,1,1,1,1},{1,0,0,0,1,1},{1,0,1,0,0,1},{1,0,0,0,1,1},{1,1,0,0,0,1}, {1,1,1,1,1,1}
};
typedef struct
{
int i; int j; int di;
}Box;
typedef struct
{
Box data[16];
int top;
}StType;
void InitStack(StType*& s)
{
s = (StType*)malloc(sizeof(StType));
s->top == -1;
}
bool StackEmpty(StType* s)
{
return(s->top == -1);
}
bool Push(StType*& s, Box e)
{
if (s->top == 15)return false;
s->top++;
s->data[s->top].i= e.i; //结构体数组的赋值
s->data[s->top].j = e.j;
return true;
}
bool Pop(StType*& s, Box e)
{
if (s->top == -1)return false;
e = s->data[s->top]; s->top--; return true;
}
bool GetTop(StType*& s, Box e)
{
if (s->top == -1)return false;
e = s->data[s->top]; return true;
}
void DestroyStack(StType* &s)
{
free(s);
}
bool mgpath(int xi,int yi,int xe,int ye)//始末位置
{
Box path[16], e;
int i, j, li, lj, di, k;
mg[xi][yi] = -1;
StType* t;
InitStack(t);
e.i = xi; e.j = yi; e.di = -1;
Push(t, e);
while (!StackEmpty(t))
{
GetTop(t, e);
i = e.i; j = e.j; di = e.di;
if (i == xe && j == ye)
{
cout << "一条迷宫路径如下:";
k = 0;
while (!StackEmpty(t))
{
Pop(t, e);
path[k++] = e;
}
for (k; k >= 1; k--)
{
cout << "(" << path[k].i << "," << path[k].j << ") ";
if ((k + 1) % 5 == 0)cout << endl;
}
DestroyStack(t);
return true;
}
bool find;//判断是否找到路线
find = false;
while (di < 4&&find!=true)
{
di++;
switch (di)
{
case 0:li = i - 1; lj = j; break;
case 1:li = i; lj = j + 1; break;
case 2:li = i + 1; lj = j; break;
case 3:li = i; lj = j - 1; break;
}
if (mg[li][lj] == 0)find = true;
}
if (find)
{
t->data[t->top].di = di;//修改原栈顶元素的di值?
e.i = li; e.j = lj; e.di = -1;
Push(t, e);//入栈
mg[li][lj] = -1;
}
else
{
Pop(t, e);
mg[e.i][e.j] = 0;
}
}
DestroyStack(t);
return false;
}
int main()
{
if (!mgpath(1, 1, M, N))cout << "迷宫无解";
}
![img](https://img-mid.csdnimg.cn/release/static/image/mid/ask/633411412436198.png "=600 #left")
为什么一直报错?内存哪里出现问题了?