我已经为 RPN 计算器编写了代码,它适用于基本运算符(+、*、/、^)以及浮点数和负数。它还计算表达式,如 (x^2 + x*4/-2) : 1 -> 5 :0.5(x 从 1 计算到 5,步长为 0.5)
我使用了一个字符堆栈。
现在,我想添加对 cos(x)、tan(x) 等函数的支持。为了达到这个目的,我需要构建一个char* 堆栈,在解析后存储诸如 sin、cos、sqrt 等单词。
问题是,在初始化堆栈时,我收到“访问冲突:地址 0x01 写入”错误。
我不知道具体为什么。会不会是 malloc() 的使用?
这些是使用堆栈的函数。
typedef struct nodo{
char *operador;
struct nodo *next;
}tipo;
typedef tipo *elemento;
typedef tipo *top;
int push(top*,char*) ;
void init(top *);
void libera(top*);
char* pop(top*);
int main(){
(...)
top op;
init(&op);
(...)
}
void init(top *pila) {
*pila = malloc(sizeof(**pila));
(*pila)->operador = NULL;
(*pila)->next = NULL;
}
void libera(top *pila) {
free(*pila);
*pila = NULL;
}
int push (top *last,char *dato){
elemento new1;
int j=strlen(dato);
new1 = (elemento)malloc(sizeof(tipo));
strncpy(new1->operador, dato,j);
new1->next=*last;
*last=new1;
;}
char* pop(top *last){
elemento aux;
char* caract;
aux = (elemento)malloc(sizeof(tipo));
aux=*last;
if (!aux)
return 0;
*last=aux->next;
strcpy(caract,aux->operador);
free(aux);
return caract;
}