代码在debug的时候报错:program received signal SIGSEGV,Segmentation fault

我是初学者,这个代码是用来解决中缀表达式转后缀表达式的,其中除了主函数和Tran函数之外都是照着《数据结构与算法分析》这本书上关于链栈的基本函数操作写的,所以Push函数出错之后我就蒙了,以下是我的代码

#include<stdio.h>
#include<stdlib.h> 
typedef struct Node *PtrToNode;
typedef PtrToNode Stack;
typedef int ElementType;
struct Node
{
    int Element;
    PtrToNode Next;
};
int IsEmpty(Stack S);
Stack CreatStack();
void MakeEmpty(Stack S);

void Push(ElementType X,Stack S);
void Pop(Stack S);
ElementType Top(Stack S);
void Tran(char *);
Stack S;

//测试栈是否为空//
int IsEmpty(Stack S)
{
    return S->Next==NULL;
} 

//创建一个空链栈//
Stack CreatStack()
{
    Stack S;
    
    S=(struct Node*)malloc(sizeof(struct Node));
    if(S==NULL)
    {
        printf("Out of space!");
    }
    S->Next=NULL;
//    MakeEmpty(S);
    return S;
}
void MakeEmpty(Stack S)
{
    if(S==NULL)
    {
        printf("Must use CreatStack first!");
    }
    else
    {
        while(!IsEmpty(S))
        {
            Pop(S);
        }
    }
}

//Push进栈//
void Push(ElementType X,Stack S)
{
    PtrToNode TmpCell;
    
    TmpCell=(Stack)malloc(sizeof(Stack));
    TmpCell->Element = X;
    TmpCell->Next=S->Next;
    S->Next = TmpCell;
} 

//返回栈顶元素//
ElementType Top(Stack S)
{
    if(!IsEmpty(S))
    {
        return S->Next->Element;
    }
    return 0;/*Return value used to avoid warning*/
    
}

//从栈弹出元素//
void Pop(Stack S)
{
    PtrToNode FirstCell;
    FirstCell = S->Next;
    S->Next = S->Next->Next;
    free(FirstCell);
} 

void Tran(char Str[])
{
    int i;
    for(i=0;Str[i]!='\0';i++)
    {
        if(Str[i] > '0' && Str[i] <= '9')
        {
            printf("%c ",Str[i]);
        }
        else if(Str[i]= 40)
        {
            Push(Str[i],S);
        }
        else if(Str[i] == '*' || Str[i] == '/')
        {
            if(Top(S)=='*' || Top(S)=='/')
            {
                printf("%c ",Top(S));
                Pop(S);
            }
            Push(Str[i],S);
        }
        else if(Str[i] == '+' || Str[i] == '-')
        {
            while(Top(S)=='*' || Top(S)=='/' || Top(S)=='+' || Top(S)=='-')
            {
                printf("%c ",Top(S));
                Pop(S);
            }
            Push(Str[i],S);
        }
        else if(Str[i] == 41)
        {
            if(Top(S) != 40)
            {
                printf("%c ",Top(S));
                Pop(S);
            }
            Pop(S);
        }
    }
    while(S -> Next != NULL)
    {
        printf("%c ",Top(S));
        Pop(S);
    }
        
}


int main()
{
    char Str[50];
    gets(Str);
    Tran(Str);
    return 0;
}

以下是我debug时出现的Push问题↓:

clipboard.png
求大神帮助!

  • 列表项目
阅读 13.3k
1 个回答

在你的Tran()函数中的

 else if(Str[i]= 40)    // 这里有问题吧,难道不是“==”?
        {
            Push(Str[i],S);
        }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进