Cout给出一个奇怪的输出

时间:2016-10-21 15:16:34

标签: c++ linux output cout

这是我已经完成的实验,即使用C ++创建一个简单的队列。

#include "Task5.h"
#include <iostream>
using namespace std;

void push(const long &i, node* &n) {
    if (n == NULL) {
        node *ptr = new node;
        ptr -> item = i;
        ptr -> next = NULL;
        n = ptr;
        cout << "Created New Node." << endl;
    }
    else {
        node *ptr = n;
        cout << "Created Pointer" << endl;
        while (ptr -> next != NULL){
            cout << "Finding Next..." << endl;
            ptr = ptr -> next;
        }
        cout << "I'm here." << endl;
        node *temp = new node;
        temp -> item = i;
        ptr -> next = temp;
        cout << "Node Created." << endl;
    }
}

long pop(node* &n) {
    if (n == NULL) cout << "HEY!!! Can't pop an empty queue." << endl;
    else {
        long val;
        node *ptr = n;
        n = n -> next;
        val = ptr -> item;
        delete ptr;
        return val;
    }
}

int main() {
    node *head = NULL;
    push(13,head);
    push(10,head);
    push(18,head);
    push(22,head);
    cout << pop(head) << endl;
    cout << pop(head) << endl;
    cout << pop(head) << endl;
    cout << pop(head) << endl;
    cout << pop(head) << endl;
    cout << pop(head) << endl;
}

这提供了以下输出:

Created New Node.
Created Pointer
I'm Here.
Node Created.
Created Pointer
Finding Next...
I'm here.
Node Created.
Created Pointer
Finding Next...
Finding Next...
I'm here.
Node Created.
13
10
18
22
HEY!!! Can't pop an empty queue.
6296192
HEY!!! Can't pop an empty queue.
6296192

所以最终结果是代码工作,但是它随机输出6296192。我想也许我拼错了一些东西或cout正在转换endl;十六进制我的实验室老师也不知道发生了什么。有人能告诉我发生了什么吗?如果有帮助,我通过Linux运行终端运行此代码。

提前致谢。

2 个答案:

答案 0 :(得分:2)

在你的功能中:

long pop(node* &n) {

如果n == NULL为真,你不会返回任何内容。所以这是UB,也可能在输出中引起这样的随机值。

答案 1 :(得分:1)

我建议在第一个cout << pop(head) << endl;上使用带有断点的调试器,并观察每次从pop返回的值。

此外,编译器可能会向您发出有关问题原因的警告,请始终注意通常意味着会发生意外情况的警告。

cout << pop(head) << endl;使用pop()返回的值,但是在空队列的情况下,没有返回值,导致未定义的行为。

相关问题