Программа расчета постфиксной нотации на C, имеющая некоторые проблемы

Я пытаюсь создать программу для запуска вычислений в постфиксной нотации с использованием C и чтения значений из командной строки unix. Я, однако, новичок в языке C, и у меня есть некоторые проблемы с правильной работой. Я получаю показания NULL и Segmentation Faults, но я не совсем уверен, как работает отладка в командной строке unix, поэтому я не могу сказать вам, где я получаю ошибку. Буду признателен за любую помощь в этом вопросе.

#include <stdio.h>
double stack(int argc, char* argv[]);

int main(int argc, char* argv[]) {


    double result;

    result = stack(argc, argv);


    printf("%s\n", result);


}

--

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
static double stck[100];
static int top = 0;

/*Push Function*/
static void push( double v){

    stck[top] = v; /* Places the value at the current top position of the stack */
    top++; /* Increases the top position of the stack */
    printf("%s\n", top);

}
/*Pop Function*/
static double pop() {

    double ret;
    ret = stck[top]; /* Stores the value of the top position in the stack to ret */
    top--; /* Decreases the top position of the stack */
    printf("%s\n", top);
    return ret; /* Returns the value of ret */

}

double stack(int argc, char* argv[]){

    double h; /* Placeholder Variable for the result of the mathematic equations during the loop */
    int i;

    for (i = 0; i <= argc - 1; i++) { /* Loops to read in all values, barring the first, for argv */

        if (strcmp(argv[i], "*") == 0) {

            double a = pop();  /* Pulls in the top value of the stack */
            double b = pop();  /* Pulls in the next top value of the stack*/
            h = b*a; /* Performs the multiplication of the two stack values */
            push(h); /* Returns the result to the top of the stack */

        } else if (strcmp(argv[i], "+") == 0) {
            printf("%s\n", "Made it here plus \0");
            double a = pop();  /* Pulls in the top value of the stack */
            double b = pop();  /* Pulls in the next top value of the stack*/
            h = b+a;  /* Performs the multiplication of the two stack values */
            push(h);  /* Returns the result to the top of the stack */

        } else if (strcmp(argv[i], "/") == 0) {

            double a = pop();  /* Pulls in the top value of the stack */
            double b = pop();  /* Pulls in the next top value of the stack*/
            h = b/a; /* Performs the division of the two stack values */
            push(h);  /* Returns the result to the top of the stack */


        } else if (strcmp(argv[i], "^") == 0) {

            double a = pop();  /* Pulls in the top value of the stack */
            double b = pop();  /* Pulls in the next top value of the stack*/
            h = pow(b,a);  /* Raises the number b by the number a power */
            push(h);  /* Returns the result to the top of the stack */


        } else if (strcmp(argv[i], "-") == 0) {

            double a = pop();  /* Pulls in the top value of the stack */
            double b = pop();  /* Pulls in the next top value of the stack*/
            h = b-a;  /* Performs the subtraction of the two stack values */
            push(h);  /* Returns the result to the top of the stack */

        } else {
            printf("%s\n", "Made it here \0");

            double ph;

            ph = (double)atof(argv[i]);
            printf("%s\n", ph);

            push(ph); /* Places the current value of argv[i] on the top of the stack */

        }

    }
    return stck[0]; /* Returns the final result of the calculation to main.c */


}

person Ranma344    schedule 10.09.2013    source источник
comment
top определяется как целое число, вы должны напечатать его, используя спецификатор целочисленного формата для printf; printf("%d\n", top);   -  person Hunter McMillen    schedule 10.09.2013
comment
Также printf(%s\n, результат); Должно быть printf(%lf\n, результат);   -  person Charlie Burns    schedule 10.09.2013


Ответы (3)


Ваши операции push и pop должны быть точной противоположностью друг другу.

Итак, если толчок

stackarray[index] = v
index++     //increment last

поп должен быть

index--     //decrement first
return stackarray[index]

в противном случае pop всегда будет возвращать значение из одного слота после последнего переданного значения.


Отладка программы, использующей аргументы командной строки, не должна сильно отличаться от отладки любой другой программы. Но вам может понадобиться прочитать документацию по отладчику, чтобы узнать, как передавать аргументы в программу. В ГДБ:

gdb> break main
gdb> run arg1 arg2 arg3 ...

То есть добавить аргументы в строку run, как если бы run было именем программы.

person luser droog    schedule 10.09.2013
comment
Эй, спасибо, чувак, ты спасаешь жизнь. Исправил, все работает как надо. Спасибо. - person Ranma344; 10.09.2013
comment
Потрясающий. Если этот ответ действительно решает проблему, вам следует нажать на галочку, чтобы принять ответ. - person luser droog; 10.09.2013

printf() спецификатор формата %s требует аргумента character array. но здесь top равно integer, поэтому вам нужно использовать спецификатор формата %d.

Изменить все

 printf("%s\n", top);  ==> printf("%d\n", top);
          ^                         ^ 
person Gangadhar    schedule 10.09.2013
comment
Спасибо за это, это действительно помогло. Теперь я вижу все свои значения и вижу, что теперь единственная проблема, с которой я сталкиваюсь, — это расчеты. - person Ranma344; 10.09.2013

Проверьте все ваши printf, чтобы убедиться, что спецификатор формата соответствует аргументу.

person Charlie Burns    schedule 10.09.2013
comment
Спасибо за это, я понятия не имел, что C имеет разные спецификаторы для каждого типа. - person Ranma344; 10.09.2013