C++ For 循环上的分段错误
在索引 19 的最后一个值之前,一切都工作正常。事实上,所有值都被打印出来,还有什么没有。一旦它打印出最终值&索引,它分段故障。我假设这是因为它正在尝试访问第 20 个值。我该如何防止这种情况发生?
主文件代码:
int index = 0;
while (index < list.length())
{
cout << list.getNextItem(index) << " " << index << "\n";
index++;
}
标题代码:
template <class Type>
Type doublyLinkedList<Type>::getNextItem(const Type& val) const
{
nodeType<Type> *current; //pointer to traverse the list
current = first; //set current to point to the first node
for (index=0; index < val; index++)
{
if (current != NULL)
{
current = current->next;
}
}
return current->info;
}//end getNextItem
Everything works fine right up until the last value of index 19. In fact, all values are printed and what not. Once it prints the final value & index, it seg faults. I am assuming this is because it is trying to access the 20th value. How would I prevent this from occurring?
MAIN FILE CODE:
int index = 0;
while (index < list.length())
{
cout << list.getNextItem(index) << " " << index << "\n";
index++;
}
HEADER CODE:
template <class Type>
Type doublyLinkedList<Type>::getNextItem(const Type& val) const
{
nodeType<Type> *current; //pointer to traverse the list
current = first; //set current to point to the first node
for (index=0; index < val; index++)
{
if (current != NULL)
{
current = current->next;
}
}
return current->info;
}//end getNextItem
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将
当前
分配给当前->下一个
。当它为null
那么,当current
为 ... null 时,您尝试返回current->info
。至少这是我的怀疑;您发布的代码不完整,不可能给您具体的答案……但这看起来确实是罪魁祸首。
You assign
current
tocurrent->next
. When it'snull
then you to try to returncurrent->info
whencurrent
is ... null.At least that's my suspicion; the code you post is incomplete and it's impossible to give you a concrete answer ... but that certainly looks like a culprit.
您的
current->info
不在空检查范围内。当current
为null时,无法访问其指针并导致seg错误Your
current->info
is outside null checking. Whencurrent
is null, you can't access its pointer and cause seg fault