无法使用堆栈分隔表达式

时间:2013-08-02 04:23:14

标签: c stack

我想获得解决问题的帮助。 我有一个表达式作为char序列,我想用堆栈分隔它,我将这个表达式分成每个操作数和运算符,每个都是序列,我想把它推入堆栈。问题是当我尝试在分离后打印表达式时,只有运算符正确显示,但操作数不正确。它们仅显示与顶部元素相同的操作数值。我不知道为什么,这是我的代码,请帮我查一下。非常感谢你!

#include "stdio.h"
#include "stdlib.h"
#include "malloc.h"
#include "string.h"
#define SIZE 100
typedef struct Stack{
    int top;
    char *data[9];
}Stack;

void init(Stack *s){
    s->top = 0;
}
void push(Stack *s, char *value){
    if(s->top < SIZE)
        s->data[s->top++] = value;
    else
        printf("stack is full");
}

bool isDigit(char s){
    if(s>='0' && s<='9')
        return true;
    return false;
}

void separate(Stack *exp,char *s){

    char temp[9];
    int n = strlen(s);  
    int l = 0,size=0;
    for(int i = 0;i<n;i++){
        if(isDigit(s[i])){
            temp[l++]=s[i];

        }
        else{           
            if(l!=0){
                temp[l]='\0';               
                push(exp,temp);
                l=0;    
            }

            char *c= (char*)malloc(sizeof(char));
            sprintf(c,"%c",s[i]);
            push(exp,c);
        }               
    }
    temp[l]='\0';
    push(exp,temp);

}

void main(){
    Stack *s = (Stack*)malloc(sizeof(Stack));
    init(s);
    char expression[100];
    printf("Enter your expression, for exp: 2-33/134+8\n");
    gets(expression);
    separate(s,expression); 
    int size = s->top;
    printf("\nsize = %d",size);
    printf("\nElements of stack are");
    for(int i = 0;i<size;i++)
        printf("\n %s",s->data[i]);
    system("pause");
}

2 个答案:

答案 0 :(得分:1)

这是因为您使用相同的内存位置temp来存储所有数字序列。这也是错误的,因为temp是函数的本地,并且在&temp[0]函数之外未定义对指针(separate)的任何访问。使用malloc和strcpy创建一个新字符串并将temp复制到其中。然后推这个新字符串。或者,您可以使用atoi创建一个整数并推送它而不是推送字符串。

答案 1 :(得分:1)

问题出在这一行

push(exp,temp);

您正在堆栈上推送局部变量temp,然后重复使用相同的数组作为下一个值。 Stack最终将指向相同的值,即最后一个值。例如。 11 + 22 + 33只能存储33个

而是使用malloc以及

分配temp

旁注:使用ctype.h中的isdigit()而不是您自己的。{/ p>