2012-02-20 138 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; 
}