請教:簡單的表達式運算為什麽不能寫入內存?
#include "stdio.h"#include "string.h"
#include "conio.h"
#include "stdlib.h"
#define STACK_INIT_SIZE 100
#define STACKINREMENT 20
#define FALSE 0
#define TRUE 1
typedef struct{
int *pBase;
int *pTop;
int StackSize;
}Stack;
typedef int BOOLEAN;
char Operator[8]={"+-*/()#"};
char Optr;
int Opnd=-1;
int Result;
char PriorityTable[7][7]=
{
{'>','>','<','<','<','>','>'},
{'>','>','<','<','<','>','>'},
{'>','>','>','>','<','>','>'},
{'>','>','>','>','<','>','>'},
{'<','<','<','<','<','=','0'},
{'>','>','>','>','0','>','>'},
{'<','<','<','<','<','0','='},
};
Stack InitStack()
{
Stack S;
S.pBase=(int*)malloc(STACK_INIT_SIZE*sizeof(int));
if(!S.pBase)
{
printf("失敗\n");
exit(-1);
}
else
{
S.pTop=S.pBase;
S.StackSize=STACK_INIT_SIZE;
}
return S;
}
void DestoryStack(Stack *S)
{
if(S->pBase)
{
free(S->pBase);
S->pTop=S->pBase=NULL;
}
}
int GetTop(Stack S)
{
return *(S.pTop-1);
}
int Push(Stack *S,int e)
{
if (S->pTop-S->pBase==S->StackSize) {
S->pBase=(int*)realloc(S->pBase,S->StackSize+STACKINREMENT*sizeof(int));
if(!S->pBase)
return 0;
S->pTop=S->pBase+S->StackSize;
S->StackSize+=STACKINREMENT;
}
*(S->pTop++)=e;
return 1;
}
int Pop(Stack *S,int *e) {
if(S->pTop==S->pBase)
return 0;
*e=*--(S->pTop);
return 1;
}
char CheckPriority(char Operator_1,char Operator_2) {
int i,j;
i=strchr(Operator,Operator_1)-Operator;
j=strchr(Operator,Operator_2)-Operator;
return PriorityTable[i][j];
}
BOOLEAN IsOperator(char ch) {
if(strchr(Operator,ch))
return TRUE;
else
return FALSE;
}
void GetInput(void) {
char ch;
char Buffer[100];
int index;
index=0;
ch=getch();
while (ch!=13&&IsOperator(ch)) {
if(ch>='0'&&ch<='9') {
printf("%c",ch);
Buffer[index]=ch;
index++;
}
ch=getch();
}
if(ch==13)
Optr='#';
else{
Optr=ch;
printf("%c",ch);
}
if(index>0) {
Buffer[index]='\0';
Opnd=atoi((Buffer));
}
else
Opnd=-1;
}
int Calc (int a ,char theta, int b) {
switch(theta){
case '+':
return a+b;
case '-':
return a-b;
case '*':
return a*b;
default:
if(b==0){
printf("除數不能為零\n");
return 0;
}
else
return a/b;
}
}
BOOLEAN EvaluateExpression() {
int temp;
char theta;
int itheta;
int a,b;
Stack OPTR=InitStack();
Stack OPND=InitStack();
GetInput();
while(Optr!='#'||GetTop(OPTR)!='#') {
if (Opnd>=0) Push(&OPND,Opnd);
switch(CheckPriority(GetTop(OPTR),Optr)) {
case '=':
Pop(&OPTR,&temp);GetInput();
break;
case '<':
if(!Push(&OPTR,Optr))
return FALSE;
GetInput();
break;
case '>':
Pop(&OPTR,&itheta);
Pop(&OPND,&b);
Pop(&OPND,&a);
theta=(char)(itheta);
Push(&OPND,Calc(a,itheta,b));
break;
}
}
if(OPND.pTop==OPND.pBase&&Opnd<0) {
printf("\n\n謝謝\n");
}
else if (OPND.pTop==OPND.pBase) {
Result=GetTop(OPND);
DestoryStack(&OPND);
DestoryStack(&OPTR);
}
return TRUE;
}
void main(void) {
if(EvaluateExpression())
printf("=%d\n",Result);
else
printf("計算有錯\n");
}
編譯沒有問題但是運行的時候就會出現:
“0x00401355”指令引用的“0xfe30684c”內存。內存不能為“read”。的錯誤.
有哪位大蝦辦一下我的 小弟無限感激!!!