2016-10-21 107 views
0

这是我已经完成的一个实验,它是使用C++创建一个简单的队列。Cout给出了一个奇怪的输出

#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运行终端运行此代码。

在此先感谢。

+6

问:当您尝试弹出空队列时,pop()返回什么值? – Mat

+2

打开编译器警告和/或停止忽略警告,告诉您在“pop”函数中出现“并非所有控制路径都返回值”的效果。那将是第一个可能出现错误的线索。我希望“实验室老师也不知道”,实际上并不真实,他们*知道,但希望你自己找到它。如果没有,几乎所有他们给你的东西是值得的(这可能不会太多)。 – WhozCraig

+0

@NathanOliver凭借停止问题的不确定性,它的确如此。 – Quentin

回答

2

在你的函数:

long pop(node* &n) { 

你不要在n == NULL情况下返回什么是真实的。所以这是UB,并且也可能在输出中导致这样的随机值。

+0

啊,这是有道理的。谢谢。我知道这是愚蠢的XD –

1

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

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

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