递归的河内塔,访问冲突/分段错误,在dev c++编译器上

Recursive Tower of Hanoi,Access violation/segmentation fault, on dev c++ compiler

本文关键字:dev c++ 编译器 错误 内塔 访问冲突 递归 分段      更新时间:2023-10-16

//以下代码产生访问冲突或分段错误//我正在寻找河内塔的简单解决方案,我应该自己写//请指出下面代码的缺陷,而不是给出你的精英代码:)

//使用三个堆栈递归求解河内塔问题

  #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);