一个用栈实现的数值转换问题,程序没有语法错误,但执行时会出现“0x00409b28"指令引用的”0xccccccc“内存,该内存不能为”written“为什么?
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define OK 1
#define ERROR 0
#define OVERFLOW 2
typedef int SElemType;
typedef int Status;
typedef struct{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
SqStack S;
/*构造空栈*/
Status InitStack(SqStack &S)
{
S.base=(SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));
if(!S.base) exit(OVERFLOW);
S.top=S.base;
S.stacksize=STACK_INIT_SIZE;
return OK;
}
/*插入e为新的栈顶元素*/
Status Push(SqStack &S,SElemType e)
{
if(S.top-S.base>=S.stacksize){
S.base=(SElemType *) realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(SElemType));
if(!S.base) exit(OVERFLOW);
S.top=S.base+S.stacksize;
S.stacksize+=STACKINCREMENT;
}
*S.top++=e;
return OK;
}
/*若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK,否则返回ERROR*/
Status Pop(SqStack &S,SElemType &e){
if(S.top==S.base) return ERROR;
e=*--S.top;
return OK;
}
/*判断S是否为空栈*/
Status StackEmpty(SqStack S)
{
if(S.top==S.base) return ERROR;
else return OK;
}
/*数制转换*/
void conversion()
{
int e,N;
SqStack S;
InitStack(S);
printf("Please input a number:");
scanf("%d",N);
while(N){
Push(S,N%8);
N=N%8;
}
while(!StackEmpty(S))
{
Pop(S,e);
printf("%d",e);
}
}
/*主函数*/
void main()
{
conversion();
}
[解决办法]
- C/C++ code
#include<stdio.h>#include<stdlib.h>#include<malloc.h>#define STACK_INIT_SIZE 100#define STACKINCREMENT 10#define OK 1#define ERROR 0#define OVERFLOW 2typedef int SElemType;typedef int Status;typedef struct{ SElemType *base; SElemType *top; int stacksize; }SqStack;SqStack S;/*构造空栈*/Status InitStack(SqStack &S){ S.base=(SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType)); if(!S.base) exit(OVERFLOW); S.top=S.base; S.stacksize=STACK_INIT_SIZE; return OK;}/*插入e为新的栈顶元素*/Status Push(SqStack &S,SElemType e){ if(S.top-S.base>=S.stacksize){ S.base=(SElemType *) realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(SElemType)); if(!S.base) exit(OVERFLOW); S.top=S.base+S.stacksize; S.stacksize+=STACKINCREMENT; } *S.top++=e; return OK;}/*若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK,否则返回ERROR*/Status Pop(SqStack &S,SElemType &e){ if(S.top==S.base) return ERROR; e=*--S.top; return OK;}/*判断S是否为空栈*/Status StackEmpty(SqStack S){ if(S.top==S.base) return ERROR; else return OK;}/*数制转换*/void conversion(){ int e,N; SqStack S; InitStack(S); printf("Please input a number:"); scanf("%d", &N); // 中断是这里的问题。。。 while(N){ Push(S,N%8); // N=N%8; // 当N小于8会出现死循环 N = N / 8; } while(!StackEmpty(S)) { Pop(S,e); printf("%d",e); }}/*主函数*/void main(){ conversion(); system("PAUSE");}