除了 vscode 之外,此代码不会 运行 在其他编译器上

This code don't run on other compiler except vscode

提供者代码用于使用堆栈将中缀转换为后缀。我到处都试过了,除了有一次我学校的计算机出现分段错误外,没有显示任何错误或警告。如果有人能解释编写代码的正确方法,那将非常有帮助,因为我找不到。 在代码中,我们扫描中缀表达式并检查它是否是一个运算符,如果它是一个运算符,我们将它压入堆栈,字符或数字进入数组。然后,如果我们发现另一个运算符的优先级高于前一个被压入的运算符,我们就会从堆栈中弹出该运算符,并且我们一直弹出,直到我们在堆栈中获得优先级较低的运算符并将其附加到数组中,这也是我们的输出。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include<ctype.h>

struct stack
{
    int size;
    int top;
    char *arr;
};
int stacktop(struct stack *sp)
{
    return sp->arr[sp->top];
}
void push(struct stack *ptr, char val)
{
    if (ptr->top == ptr->size - 1)
    {
        printf("Stack is full\n");
    }
    else
    {
        ptr->top++;
        ptr->arr[ptr->top] = val;
    }
}
char pop(struct stack *ptr)
{
    int a;
    if (ptr->top == -1)
    {
        printf("\n");
    }
    else
    {
        a = ptr->arr[ptr->top];
        ptr->top--;
        return a;
    }
}
int isoperator(char symbol)
{
    if (symbol == '^' || symbol == '*' || symbol == '/' || symbol == '+' || symbol == '-')
    {
        return 1;
    }
    else
    {
        return 0;
    }
}
int precedence(char symbol)
{
    if (symbol == '^')
    {
        return (3);
    }
    else if (symbol == '*' || symbol == '/')
    {
        return (2);
    }
    else if (symbol == '-' || symbol == '+')
    {
        return (1);
    }
    else
    {
        return (0);
    }
}
char *infix_to_postfix(char *infix)
{
    struct stack *sp = (struct stack *)malloc(sizeof(struct stack));
    sp->size = 50;
    sp->top = -1;
    sp->arr = (char *)malloc(sp->size * sizeof(char));
    char *postfix = (char *)malloc(strlen((infix) + 1) * sizeof(char));
    int i = 0, j = 0, x = 0;
    while (infix[i] != '[=12=]')
    {
        if (infix[i] == '(')
        {
            push(sp, infix[i]);
        }
        else if( isdigit(infix[i]) || isalpha(infix[i])){
            postfix[j]=infix[i];
            j++;
        }
        else if (isoperator(infix[i])==1)
        {
            x=pop(sp);
            while(isoperator(x)==1 && precedence(x)>=precedence(infix[i])){
                postfix[j]=x;
                j++;
                x=pop(sp);
            }
            push(sp, x);
            push(sp, infix[i]);
        }
        else if (infix[i] == ')')
        {
            x = pop(sp);
            while (x != '(')
            {
                postfix[j] = x;
                j++;
                x = pop(sp);
            }
        }
        i++;
    }
    while (!(sp->top == -1))
    {
        postfix[j] = pop(sp);
        j++;
    }
    postfix[j] = '[=12=]';
    return postfix;
}

int main()
{
    char *infix;
    printf("Enter your expression\n");
    scanf("%s",infix);
    printf("Postfix is %s", infix_to_postfix(infix));
    return 0;
}

指针变量 char *infix 没有指向任何东西,所以它与 VSCode 和其他编译器无关。它正在 VSCode.

上工作真是太幸运了

您应该静态 char infix[100] 或动态 char *infix = (char *)malloc(100) 分配一些内存。

此外,您的 pop 功能有问题。你应该总是 return 一个 char 来自这个函数,不仅仅是在某些条件下。