我想获得解决我的问题的帮助。我有一个表达式作为char序列,我想使用堆栈将其分离,我将该表达式拆分为每个操作数和运算符,它们中的每一个都是序列,我想将其压入堆栈。问题是当我尝试在分离后打印表达式时,只有运算符可以正确显示,但操作数不正确。它们仅显示与top元素相同的操作数值。我不知道为什么,这是我的代码,请帮助我检查一下。太感谢了!
#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");
}
这是因为您使用相同的存储位置temp
来存储所有数字序列。这也是错误的,因为它temp
是函数的本地函数,并且&temp[0]
在separate
函数外部未定义对指针()的任何访问。使用malloc和strcpy创建一个新字符串并将temp复制到其中。然后推这个新的字符串。或者,您可以使用atoi
创建一个整数并压入它而不是压入字符串。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句