Я получаю ошибку сегментации в своем коде и не могу объяснить, почему.Я пишу программу, которая принимает инфиксное выражение и преобразует его в постфикс с помощью стукта стека.
Вот мой основной и объявление методов, а также объявление моего стека:
#define LINELN 72
#define STACKSZ 25
#define NEWLN '\n'
#include <stdlib.h>
#include <string.h>
typedef struct stack {
char data[STACKSZ];
int top;
} stack;
void initstk(stack *s1);
int emptystk(stack s1);
char peek(stack s);
int getline(char infix[]);
void push(char item, stack *s);
char pop(stack *s);
int preced(char x);
void processinfix(char infix[], int l, char postifx[]);
#include <stdio.h>
int main() {
char infix[LINELN];
char postfix[LINELN];
processinfix(infix,getline(infix),postfix);
exit(0);
}
Мои методы, которые я протестировал и которые работают, являются основными методами манипулирования стеком:
//makes top of stack -1
void initstk(stack *s1) {
s1->top=-1;
}
//returns 1 if stack is empty, 0 otherwise
int emptystk(stack s) {
if(s.top == -1){
return one;
}
else{
return 0;
}
}
//peeks at top of the stack
char peek(stack s) {
return s.data[s.top];
}
//pushes value to top of stack
void push(char item, stack *s) {
s->top = s->top +1;
s->data[s->top] = item;
}
//pops off the top of stack and returns it
char pop(stack *s) {
char x;
x = s -> data[s->top];
s-> top =s->top-1;
return x;
}
//gives character a precedence number according to what it is
int preced(char x) {
switch (x) {
case '(':
case ')':
return 3;
case '*':
case '/':
case '%':
return 2;
case '+': case '-':
return 1;
}
return 0;
}
У меня есть функция getLine (), которая принимает пользовательский ввод, который будет выражением, например: A + B,и сохраняет его в infix []
int getline(char infix[]){
char c;
int i=0;
printf("Type in your expression");
while((c = getchar()) !=NEWLN && i <= LINELN && c != ' ' ){
infix[i]=c;
i++;
}
return i;
}
Моя следующая функция - сортировать выражение infix и помещать его в постфикс []
void processinfix(char infix[], int inlen, char postfix[])
{
stack s1;
initstk(&s1);
printf("%d characters are in infix\n", inlen);
int i =0;
int k=0;
// while "i" isnt bigger then the number of elements in infix
while( i<sizeof(infix)){
/* if infix[i] is a letter send it to post fix right away,
increment inlen down one because infix is now smaller by 1 */
if (('a'<= infix[i]&& infix[i] <= 'z') ||( 'A' <= infix[i]&& infix[i]
<='Z')){
printf("%c is a letter, sending to postfix\n", infix[i]);
postfix[k] = infix[i];
inlen--;
printf("infix has shrinked by 1\n");
k++;
}
/* else if infix[i] has a higher precedence then whats on top of stack
push infix[i] on to stack and increment inlen down 1 */
else if(preced(infix[i])>preced( s1.data[s1.top])){
push(infix[i],&s1);
inlen--;
printf("infix has shrinked by 1\n");
printf("%c is top of stack\n", s1.data[s1.top]);
}
/* else if infix[i] is lower or equal to whats on top of stack. put
top of stack into postfix[] until infix[i] is higher precedene then
top of stack. then put it on top of stack and decrease */
else if(preced(infix[i]) <= preced(s1.data[s1.top])){
printf("%c is higher or equal then %c\n", s1.data[s1.top],
infix[i]);
while (preced(infix[i])<=preced(s1.data[s1.top])){
postfix[k] = s1.data[s1.top];
printf("%c is put into postfix expression\n", s1.data[s1.top]);
pop(&s1);
k++;
}
push(infix[i], &s1);
inlen--;
printf("%c is now the top\n", s1.data[s1.top]);
}
// if nothing is left in infix pop stack until s1.top = -1
if(inlen==0){
printf("nothing left in infix\n");
while (s1.top!= -1){
printf("sendin %c to postfix\n", s1.data[s1.top]);
postfix[k]=s1.data[s1.top]
pop(&s1);
k++;
}
break;
}
i++;
}
// print postfix
int x=0;
while(x<= sizeof(postfix)){
printf("%s",postfix[x]);
x++;
}
printf("\n");
}
Вывод, который я получаю
Type in your expressionA+B
3 characters are in infix
A is a letter, sending to postfix
infix has shrinked by 1
infix has shrinked by 1
+ is top of stack
B is a letter, sending to postfix
infix has shrinked by 1
nothing left in infix
sending + to postfix
Segmentation fault
так что все работает нормально, пока не столкнется с
if(inlen==0){
printf("nothing left in infix\n");
while (s1.top!= -1){
printf("sendin %c to postfix\n", s1.data[s1.top]);
THIS LINE -> postfix[k]=s1.data[s1.top]<-THIS LINE
pop(&s1);
k++;
}
Postfix [k] = s1.data [s1.top];работает раньше в циклах while, но только не здесь.Есть идеи, почему?