一切正常工作,直到索引19的最后一个值。实际上,所有的值都打印出来,而不是。一旦它打印出最终值&索引,它就会发生故障。我假设这是因为它试图访问第20个值。我将如何防止这种情况发生?For循环上的C++分段错误
主要文件代码:
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
这是一个非常奇怪的实现。在'getNextItem'中'index'初始化了哪里?为什么列表像穷人的矢量一样遍历? –
另外,神奇数字19和20从哪里来? –