0

所以我不断收到消息无效表达式“...”总线错误(核心转储)如果我输入 ./rpcalc “...”如果我只是输入命令行 ./rpcalc 1 我得到分段错误(核心转储)消息。这是我的全部代码,我将不胜感激。

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define max 10
#define NUMBER 'n'



int main(int argc, char *argv[])
{
  double tmp;
   char c;

  if(argc <= 1) {
    fprintf(stderr,"invalid call\n");
    return 1;
  }

    while(--argc)
       {
         c = getop(*++argv);
        switch(c)
          {
         case NUMBER:
          push(atof(*argv));
          break;
         case '+':
          push(pop() + pop());
          break;
         case '-':
          tmp = pop();
          push(pop() - tmp);
          break;
         case '*':
          push(pop() * pop());
          break;
         case '/':
          tmp = pop();

          if(!tmp){
          printf("can't divide by 0\n");
          }
          else{
          push(pop()/tmp);
          }
          break;
         default:
           printf("invalid expression %s\n", *argv);
         }
      }
    printf("%g\n",pop());
    return 0;
}


int push (int stack[max], int *top, int *data)
{
 if(*top == max -1)
    return(-1);
  else
    {
      *top = *top +1;
      stack[*top] = *data;
      return(1);
    }
}

int pop(int stack[max], int *top, int *data)
{
  if(*top == -1)
    return(-1);
  else
    {
      *data = stack[*top];
      *top = *top - 1;
      return(1);
    }
}

 static int isNumber(const char *s){
  if(*s == '-' || *s == '+') s++;
  if(*s == '\0'){
    return 0;
  }

  while (isdigit(*s)) s++;

  if(*s == 'e' || *s == 'E'){
    s++;
    while(isdigit(*s)) s++;
  }
  return *s == '\0';
}

int getop(const char *op){
  return isNumber(op) ? NUMBER : *op;
}
4

1 回答 1

0

gcc -Wall -ansi -pedantic

首先,您可能不应该返回静态 int。返回 char 或 int 或 unsigned int。

下一步:您正在使用不正确的参数调用函数:

第 28 行:

push(atof(*argv));

这不是您定义函数的方式。

int push (int stack[max], int *top, int *data);

它需要一个 stack[max] 数组、一个 int 指针和另一个 int 指针

传入浮点数是不正确的。

实际上,看起来您的所有函数调用都带有不正确的参数。

于 2015-03-09T02:00:18.040 回答