2012-02-20 143 views
-1

我正在寫一個程序,添加,刪除和顯示節點(這是雙向鏈接)及其組件,但每當我嘗試檢索節點並顯示它的組件時,我得到此錯誤:C++鏈接列表搜索錯誤:STATUS_ACCESS_VIOLATION

2 [main] a 4640 exception::handle: Exception: STATUS_ACCESS_VIOLATION 

2875 [主]一4640 open_stackdumpfile:轉儲堆棧跟蹤a.exe.stackdump

我已經把範圍縮小到一個應該搜索,看看我的.h文件中的搜索功能鏈接列表中有一個節點正在搜索帳號。該函數返回之前的節點或「前一個」節點。

這裏是我的搜索功能:

bool searchListByAcctNum (int searchKey, nodePtr *prevOut) 
    { 
     bool found = false; 
     nodePtr p = headNum; 
     nodePtr prev = NULL; 
     while (p != NULL) 
     { 
     if (p->acctNum < searchKey) 
     { 
      prev = p; 
      p = p->nextNum; 
     } 
     else 
     { 
      if (p->acctNum == searchKey) 
       found = true; 
      p = NULL; 
     } 
     } 
     *prevOut = prev; 
     return found; 

如果有人可以幫助我的人,我會感激!

+0

你如何在創建列表時爲節點分配內存? – Naveen 2012-02-20 09:30:24

+1

提供的信息不足。 – 2012-02-20 09:31:51

+0

您的鏈接列表已損壞並且包含陳舊的指針,或者'prevOut'是'NULL'(或無效指針)。 – 2012-02-20 09:32:23

回答

0

看起來您的列表可能已損壞,或者您傳遞的接收前一節點的指針無效,因爲該代碼看起來沒問題。但是,在我看來,它可以寫得更簡單:

bool searchListByAcctNum (int searchKey, nodePtr *prevOut) { 
    /// Start at beginning of list, use pointer variable to hold previous. 

    nodePtr p = headNum; 

    *prevOut = = NULL; 

    // Process entire list, will exit early if need be. 

    while (p != NULL) { 
     // If past it, just return false, caller should ignore prevOut. 

     if (p->acctNum > searchKey) 
      return false; 

     // If equal, return true, prevOut holds previous or NULL if found at start. 

     if (p->acctNum == searchKey) { 
      return true; 

     // Save previous and advance to next. 

     *prevOut = p; 
     p = p->next; 
    } 

    // Reached end of list without finding, caller should ignore prevOut. 

    return false; 
}