一切正常工作,直到索引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從哪裏來? –