递归的河内塔,访问冲突/分段错误,在dev c++编译器上
Recursive Tower of Hanoi,Access violation/segmentation fault, on dev c++ compiler
//以下代码产生访问冲突或分段错误//我正在寻找河内塔的简单解决方案,我应该自己写//请指出下面代码的缺陷,而不是给出你的精英代码:)
//使用三个堆栈递归求解河内塔问题
#include <iostream>
using namespace std;
#define max 50
typedef struct stack{ //union?
int tos;
int els[max]; //stack->els[1] = tos
}stack; //template stack?
void toh(int, stack * , stack *, stack *);
void display(stack * );
int main(){
cout<<"Enter the number of discs ( <=50 ) in Tower of Hanoin";
int n;
cin>>n;
stack *A,*B,*C;
toh(n, A,B,C);
system("pause");
return 0;
}
void toh( int n, stack *A, stack *B, stack *C){
if ( n == 1 ) {
int temp = A->els[A->tos]; //switch case i=1,2,3 tos[i]
A->tos -= 1; //OR stack * A, A->tos?
C->tos += 1;
C->els[C->tos] = temp;
// push the popped item in stack C
cout<<"At";
display(A);
cout<<"nBt";
display(B);
cout<<"nCt";
display(C);
}
else {
toh( n-1, A, C, B);
toh( 1, A, B, C);
toh( n-1, B, A, C);
}
}
void display(stack * X){ //and not int[] stack
cout<<"The stack elements are :n";
for( int i = 1; i <= X->tos; i++){//impo to start with 1 if tos = 0 init
cout<<X->els[i];
cout<<"t";
}
}
由于上面给出的微妙提示有点太微妙了,请看下面的代码:
stack *A,*B,*C;
toh(n, A,B,C);
指针永远不会初始化。因此它们的值是未知的。
最简单的修复方法是在main的堆栈中分配它们,然后将指针传递给toh函数:stack A,B,C;
toh(n, &A,&B,&C);
相关文章:
- 请发现它在 dev 中工作的错误,但在 hackerrank 中不起作用
- 无法在 dev-c++ 上编译程序?
- Dev c++ mingw 不再编译
- 如何在 Windows 上将bcrypt_gensalt与 /dev/urandom 一起使用?
- 我正在使用dev c ++,但收到错误(C++98'array'必须由构造函数初始化)
- dev Wx Dev C++ vs Graphics.h?
- dev如何在C++中比较二进制数
- 在linux中为c++dev配置VSCode
- DEV C++ 第 69 行 [错误] ISO "for" 范围更改了"i"的名称查找 [-允许]
- dev在试图从dev c++mingw 4.8.1中的文件读取时接收分段错误
- 我有一个C++函数,它在Dev C++中编译,但在G++中不编译
- 写入/dev/ttyS0后读取0字节
- 如何将 stderr 重定向到 /dev/null
- 如何创建C++DLL(使用DEV -C++)并在MT4脚本中使用(逐步)
- auto 关键字在 Dev c++ 中不起作用
- 从 win 7 升级到 Win 10 后,出现 Dev-C++ makefile.win 编译错误
- 如何检测 ofstream 是否正在写入 /dev/null
- 如何将 libproxy-dev 链接到现有的 cmake 项目(C++)?
- 在哪里调用主函数(dev c ++)
- mmap with /dev/input/event*