为什么不打印任何东西
Why doesnt cout print anything?
我试图在以下代码中输出链表中的字符,但我的cout
在printList
函数中不会打印任何东西。我不能准确地指出为什么以及如何在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
,以便在屏幕上看到实际输出。
相关文章:
- 打印时有二叉树问题.用户输入不打印任何内容
- main() 中的 std::cout 在调试期间不会在调试控制台中打印任何内容
- 为自定义打印调试实现传递任何类型的变量
- cout 不打印任何内容到控制台
- 为什么字符串没有更新并且最终没有打印任何内容
- 我如何处理 TMP 以避免打印任何东西
- 为什么我的主文件.cpp不打印头文件中的任何内容
- 我想使用 "cout" 命令慢慢打印文本,但我真的找不到任何解决方案
- 泛型函数反向打印任何矢量,编译器出错
- Cout 一个字符串可以打印任何内容到屏幕上
- "cout<<count<<endl;"没有打印任何内容
- 使用 C++ shell 为 C++ 中的 2 D 动态数组赋值,控制台不会打印出任何内容
- 我的esp32打印奇怪的字符,但我做任何事情
- 为什么循环迭代不打印任何东西?
- 函数不打印任何 c++
- 下面的代码没有打印任何东西
- 我的 c++ 程序中的字符数组不会打印任何内容
- 如果否则错误:如何使其打印任何数字
- 是否有任何操纵器将枚举值打印为字符串?
- 该程序不会在任何地方打印系统日志?