【问题标题】:Why doesnt cout print anything?为什么 cout 不打印任何东西?
【发布时间】:2014-08-12 20:10:32
【问题描述】:

我试图在下面的代码中输出我的链表中的字符,但我在printList 函数中的cout 不会打印任何内容。我无法准确了解为什么以及如何在链接列表中打印我的字符。

#include <iostream>
#include <stdlib.h>

using namespace std;

typedef struct linkedListNode{
    char obj;
    linkedListNode *next;
}node;

void insertLinkedList(char *p,node *head){
    node *end = head;
    while(*p != '\0'){
        node *temp = (node *)malloc(sizeof(node));
        temp -> obj = *p;
        end -> next = temp;
        end = temp;
        p++;
    }
}


void printList(node *head){
    node *temp = head;
    while(temp){
        cout << temp->obj << ",";
        temp = temp -> next;
    }
}

int main() {
    node *HEAD = (node *)malloc(sizeof(node));
    char p[] = "nitin";
    insertLinkedList(p,HEAD);
    printList(HEAD);
    return 0;
}

如果我的调试技能没有让我失望,那么列表确实会被填充。请帮忙。

谢谢!

【问题讨论】:

    标签: c++ pointers char


    【解决方案1】:

    您忘记终止链接列表,因此应用程序崩溃。当我使用 VS2013 在 Windows 8.1 上运行它时,我实际上看到了崩溃前的输出。但这可能是好运。在另一台机器/配置上,它可能会在刷新控制台输出之前崩溃,因此您可能永远看不到它确实有效。

    void insertLinkedList(char *p, node *head){
        node *end = head;
        while (*p != '\0'){
            node *temp = (node *)malloc(sizeof(node));
            temp->obj = *p;
            end->next = temp;
            end = temp;
            p++;
        }
        end->next = NULL;
    }
    

    在调试器中单步调试代码应该清楚发生了什么。

    【讨论】:

    • 我在发帖时发布了它。对不起。
    【解决方案2】:

    您的代码会按照您告诉它的方式输出所有内容,但是一旦 printList 落在列表末尾,它就会触发未定义的行为。

    首先,您永远不会初始化新节点的next 指针,这意味着您的列表没有正确终止。它实际上正确打印了所有内容,但它没有停止正确打印,因为您的列表没有终止。您必须记住将最后一个新元素的next 指针设置为空指针。 (这也适用于 head 元素。)

    其次,标准输出是行缓冲的。不要忘记输出std::endl 以在屏幕上查看实际输出。

    【讨论】:

      猜你喜欢
      • 2012-12-30
      • 2014-07-03
      • 2011-05-27
      • 2011-10-27
      • 1970-01-01
      • 2020-01-10
      • 1970-01-01
      • 2019-02-20
      • 1970-01-01
      相关资源
      最近更新 更多