功能不会返回

时间:2014-04-02 15:27:00

标签: c linked-list

struct m_queue{
       int ndata;
       struct m_queue* pnext;
       struct m_queue* pdown;
       };

 int search(struct m_queue* list,int key){  //returns the index where it founded the key, return -1 if key is not found
        struct m_queue* temp;//searches horizontal
        struct m_queue* run;//searches downward
        int i;
        temp = list;

        run = temp->pdown;

        getch();
        while(temp!=NULL){

            getch();
            while(run!=NULL){
                if(run->ndata == key)
                    return temp->ndata;
                else
                    run = run->pdown;
            }
            temp = temp->pnext;
            run = temp->pdown;

        }
        printf("returning -1");
        getch();
        return -1;

    }

我已经检查了其他功能,我非常确定没有任何缺陷,但每当我调试我的程序时,它总是突出显示段" run = temp-> pdown"。这个函数不会返回-1,只要找到密钥就返回。这是用c语言编码的

3 个答案:

答案 0 :(得分:1)

如果tempNULL,则run = temp->pdown;是无效操作。

}
temp = temp->pnext;
if (temp!=NULL)  //add this line
    run = temp->pdown;

答案 1 :(得分:0)

问题在于以下几点:

      temp = temp->pnext;
      run = temp->pdown;

temp为NULL时会发生什么?您正在尝试访问temp->pdown而不检查temp是否为NULL。

答案 2 :(得分:0)

   //run = temp->pdown;                    //this statement not needed

    getch();
    while(temp!=NULL){
        run = temp->pdown;                 //add this statement
        getch();
        while(run!=NULL){
            if(run->ndata == key) 
               return temp->ndata;
            else
                run = run->pdown;
        }
        temp = temp->pnext;
       // run = temp->pdown;              // this statement not needed
  }

进行此更改以避免在为NULL时访问temp。