C++ For 循环上的分段错误

发布于 2024-12-05 01:20:21 字数 764 浏览 0 评论 0原文

在索引 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

荆棘i 2024-12-12 01:20:21
for (index=0; index < val; index++)
{
    if (current != NULL)
    {
        current = current->next;
    }
}
return current->info;

您将当前分配给当前->下一个。当它为 null 那么,当 current 为 ... null 时,您尝试返回 current->info

至少这是我的怀疑;您发布的代码不完整,不可能给您具体的答案……但这看起来确实是罪魁祸首。

for (index=0; index < val; index++)
{
    if (current != NULL)
    {
        current = current->next;
    }
}
return current->info;

You assign current to current->next. When it's null then you to try to return current->info when current 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.

一直在等你来 2024-12-12 01:20:21

您的 current->info 不在空检查范围内。当current为null时,无法访问其指针并导致seg错误

Your current->info is outside null checking. When current is null, you can't access its pointer and cause seg fault

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文