繁体   English   中英

Cout发出奇怪的输出

[英]Cout giving a weird output

这是我完成的一个实验,它是使用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运行的终端运行此代码。

提前致谢。

在您的职能:

long pop(node* &n) {

如果n == NULL则不返回任何内容。 因此这是UB,并且可能还会在输出中导致此类随机值。

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

同样,编译器可能会向您发出有关问题原因的警告,请始终注意警告,它通常意味着意想不到的事情会发生。

cout << pop(head) << endl; 使用pop()返回的值,但在队列为空的情况下,不返回任何值,从而导致未定义的行为。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM