Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 函数中返回语句处的Seg错误_C++_Segmentation Fault_Fault_Infix Notation_Postfix Notation - Fatal编程技术网

C++ 函数中返回语句处的Seg错误

C++ 函数中返回语句处的Seg错误,c++,segmentation-fault,fault,infix-notation,postfix-notation,C++,Segmentation Fault,Fault,Infix Notation,Postfix Notation,我的程序应该将提示从中缀转换为后缀。到目前为止,通过调试器和各种其他方法,我已经找到了我出错的确切位置,但不明白为什么 这是我的密码: 这是itop.h: using namespace std; #include <cstdlib> #include <iostream> class sNode{ public: char data; sNode *next; }; class stack{ public:

我的程序应该将提示从中缀转换为后缀。到目前为止,通过调试器和各种其他方法,我已经找到了我出错的确切位置,但不明白为什么

这是我的密码:

这是itop.h:

using namespace std;
#include <cstdlib>
#include <iostream>

class sNode{
    public:
       char data;
       sNode *next;
};

class stack{
    public:
        sNode *head;
        void push (char);
        sNode pop();
        int rank(char);
        stack()
        {
        cout << "Initiliazing stack." << endl;
        }
};
使用名称空间std;
#包括
#包括
类势垒{
公众:
字符数据;
斯诺德*下一个;
};
类堆栈{
公众:
斯诺德*头;
无效推送(char);
snodepop();
整数秩(char);
堆栈()
{

cout您的代码中有许多错误。您的堆栈实现是错误的。
push()
例如,只会反复设置
head
。这导致堆栈类只能保存一个元素。
next
从未设置为任何值,因此它包含随机垃圾。更进一步,您有:

for(int i=0; i<sizeof(temp2); i++)

for(inti=0;ifix1:编写一个合适的构造函数

    stack()
    {
    head=NULL;
    cout << "Initiliazing stack." << endl;
    } 
修正3:在使用堆栈数据之前检查堆栈是否为空

else if(!s.empty() && s.rank(temp2[i]) < s.rank(s.head->data))
{
 ...
}
else如果(!s.empty()&&s.rank(temp2[i])data))
{
...
}

修正4:修正其余的代码逻辑。

为什么要创建变量
num
?可以直接返回整数。我只是想简化代码。:)@OP:请给我们看一下调用函数。调用函数是必需的。返回时出现segfault通常是您在返回之前的某个地方损坏堆栈的一种症状-但不清楚您在这里做什么会导致这种情况。我想可能是返回一个直接整数的问题。我只是没有看到错误当函数的返回类型为int时,返回int永远不会是问题。当然,如果您以不同方式使用函数的返回值或与其他数据类型一起使用函数的返回值,则在调用函数中也可能出现seg错误。您可以发布调用函数代码吗?@askmish Nope。普通的老眼睛。这意味着,我可能错了:-)使用
sn->next=head;
head=sn;head只是堆栈的顶部,所以当我在顶部添加一些东西时,新节点必须成为head,下一个指向旧的head。不过,感谢您提供的大小。@OP:您也可以使用STL堆栈。我们不允许使用堆栈库。非常感谢你,askmish!检查空堆栈真的很有帮助。现在我只需要找出中缀到后缀的正确顺序(基本上就是本练习的全部要点),然后我就完成了。
            else if(x == '+' || x == '-')
            {
                    num = 2;
                    // cout << "Checking if + or -" << endl;
                    return num;
                    // cout << "After return." << endl;
            }
for(int i=0; i<sizeof(temp2); i++)
    stack()
    {
    head=NULL;
    cout << "Initiliazing stack." << endl;
    } 
int stack::empty()
{
    if(head == NULL)
      return true;
    else
      return false;
}
else if(!s.empty() && s.rank(temp2[i]) < s.rank(s.head->data))
{
 ...
}