进制转换
//SqStack.h
#define MAXSIZE 100
#define FALSE 0 //函数结果状态代码
#define TRUE 1
#define OVERFLOW -2
#define OK 1
#define INFEASIBLE -1
#define ERROR 0
typedef int SElemType;
typedef bool Status;
typedef struct{
SElemType *base; //栈底指针
SElemType *top; //栈顶指针
int stacksize; //栈可用最大容量
}SqStack;
Status InitSqStack(SqStack S); //初始化
Status pop(SqStack &S,int &e); //出栈操作
Status Push(SqStack &S,int e); //入栈操作
// SqStack.cpp
#include"SqStack.h"
#include
Status InitSqStack(SqStack S) //初始化
{
S.base=(SElemType*)malloc(MAXSIZE*sizeof(SElemType)); //S.base=new SElemType[MAXSIZE];
if(!S.base) exit(OVERFLOW);
S.base=S.top;
S.stacksize=MAXSIZE;
return OK;
}
Status Push(SqStack &S,int e) //入栈操作
{ if(S.top-S.base==S.stacksize) //栈满
return ERROR;
else
*S.top++=e;
return OK;
}
Status pop(SqStack &S,int &e) //出栈操作
{
if(S.top==S.base) //栈空
return ERROR;
else
e=*--S.top;
return OK;
}
//main.cpp
#include
#include"SqStack.h"
int main()
{ int N,d,i=0,j,e;
SqStack S;
if(InitSqStack(S))
printf("初始化成功!\n");
else
printf("初始化失败!\n");
printf("十进制数N=");scanf("%d",&N);printf("\n");
printf("要转换的进制d=");scanf("%d",&d);printf("\n");
while(N)
{
Push(S,N%d);
++i;
N=N/d;
}
for(j=i;j>=1;j--)
{
pop(S,e);
printf("%d转换为%d进制=%d",N,d,e);
}
return 0;
}
运行那个Push函数
这个问题用开发环境自带的调试功能就能定位是哪一行代码导致程序崩溃。
我用的是vscode,如下图
原因在于S.top没有初始化
Status InitSqStack(SqStack S) //初始化
{
S.base=(SElemType*)malloc(MAXSIZE*sizeof(SElemType)); //S.base=new SElemType[MAXSIZE];
if(!S.base) exit(OVERFLOW);
S.base=S.top;
S.stacksize=MAXSIZE;
return OK;
}
S.base=S.top;这句写反了,应该是S.top = S.base;
但这还有一个问题,这里的S是形参,改变形参并不能改变传入函数的实参,所以InitSqStack这个函数实际并没有起到任何作用。
因为我看到你代码里有#include <stdio.h>头文件,推测你用的是C语言而不是C++,所以InitSqStack函数的参数应改为指针
Status InitSqStack(SqStack *pS) //初始化
{
pS->base=(SElemType*)malloc(MAXSIZE*sizeof(SElemType)); //pS->base=new SElemType[MAXSIZE];
if(!pS->base) exit(OVERFLOW);
pS->base = pS->top;
pS->stacksize=MAXSIZE;
return OK;
}
调用InitSqStack处改为
if(InitSqStack(&S))
另外程序应该还有其他问题,因为我测试了一下,计算结果并不正确。不过还是你自己先尝试解决更有助于学习