为什么不打印任何东西

Why doesnt cout print anything?

本文关键字:任何东 打印 为什么不      更新时间:2023-10-16

我试图在以下代码中输出链表中的字符,但我的coutprintList函数中不会打印任何东西。我不能准确地指出为什么以及如何在linkedlist中打印我的字符。

#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 != ''){
        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;
}

如果我的调试技能没有失败,列表确实会被填充。请帮助。

谢谢!

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

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

在调试器中遍历代码应该可以清楚地知道发生了什么。

你的代码输出一切就像你告诉它,但它触发未定义的行为一旦printList落在列表的末尾。

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

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