为什么我的C++代码在以下打印链表的代码片段中显示分段错误?
Why does my C++ code show segmentation fault in the following snippet of printing a linked list?
我有这个问题,我必须编写一个函数来打印完整的链表。您能否解释为什么我会收到此错误以及如何解决它
/*
Print elements of a linked list on console
head pointer input could be NULL as well for empty list
Node is defined as
struct Node
{
int data;
struct Node *next;
}
*/
void Print(Node *head)
{
cout<<"test";
while(head->next!=NULL)
{
cout<<(head->data)<<endl;
head=head->next;
}
}
?
您不检查参数头是否为 NULL。如果调用 Print(NULL(,则正在尝试访问空指针,并且可能会发生分段错误。
void Print(Node *head)
{
if(head == nullptr) return;
cout<<"test";
while(head->next!=NULL)
{
cout<<(head->data)<<endl;
head=head->next;
}
}
相关文章:
- 这个带有模板<类 Vector 的C++代码片段有什么问题>
- 这两个代码片段相似,但显示的结果不同
- 如何替换此示例代码片段中已弃用的handler_type_t或 boost::asio::handler_type?
- 如果我在下面的代码片段中添加"delete[] d;",为什么我得到零?
- 我遇到了这个代码片段,不明白. 它递归检查 C++ 字符串中是否存在大写字符
- 任何人都可以解释一下我是否需要 & 在第一个代码片段中
- 提取狮身人面像文档中的C++代码片段
- 为什么此代码片段有效?如何取消引用空点?
- 无法在这个基本的Qt代码片段中找到错误,但我被告知它肯定存在?
- 这个代码片段中会发生死锁吗?为什么
- 这个代码片段中的while循环是如何工作的
- 在给定的代码中,有人可以解释一下(int i = 0; i<len; i++)count[str[i]]++的代码片段;
- 为什么我的C++代码在以下打印链表的代码片段中显示分段错误?
- 为什么这两个代码片段具有相同的效果?
- 以下代码片段的时间复杂度是多少?
- 为什么以下代码片段存在编译错误
- 如何在此代码片段中创建 begin() 指针
- 为什么这个简短的模板代码片段有效
- 为什么这个代码片段在 C 和 C++ 中生成完全不同的汇编代码?
- 我应该修复这个晦涩而优雅的C 代码片段吗?