2012-10-31 31 views
0

當我運行這個程序並輸入一個值來搜索程序崩潰(exe已停止工作,關閉程序)。一旦輸入值65的時候,我得到了數無限循環未發現輸入要搜索的值(-1退出):C++程序崩潰(數組和2指針binsearch函數)

下面是代碼:

#include <iostream> 
using namespace std; 

void Search(int[], int * , int *); 

int main() 
{ 

    int i,KEY,num, array[] = {98,87,76,65,54}; 


    for(i=0;i<5;i++) 
    cout << array[i] << " "; 

    Search(array, &KEY, &num); 

    cout << endl; 
    system("pause"); 
    return 0; 
} 

void Search(int arr[5], int * current, int * numel) 
{ 

    int low, high,search,N; 

    cout << "\nWhat Number would you like to search for? (-1 to quit) : "; 
    cin >> search; 

    while(search!=-1) 
    { 
    low=0; 
    high=N-1; 
    while(low<=high) 
    { 
     *current=(low+high)/2; 
     if (search > arr[*current]) 
     low=*current+1; 
     else if(search<arr[*current]) 
     high=*current-1; 
     else 
     break; 
    } 
    if(arr[*current]==search) 
     cout << "Number found at index " << *current << endl; 
    else 
     cout << "Number not found." << endl; 
    cout << "Enter a value to search (-1 to quit) :"; 
    } 
    return; 
} 
+1

你的問題是什麼? –

+0

我的問題是爲什麼我的代碼失敗/崩潰? – user1787130

+0

我建議你自己去研究一下崩潰。首先使用調試器或插入輸出語句來查找崩潰發生的位置。然後從那裏開始嘗試找出問題所在。 –

回答

0

N尚未初始化,所以誰知道這個說法:

high=N-1; 

會做?

+0

更改int低,高,搜索,N;到低,高,搜索,N = 5; – user1787130

+0

這是否改變了一切?代碼可能還有其他一些問題。使用調試器或者拋出一些'printf()'語句(如果你不想使用調試器出於某種原因)可能會提供一些見解。 –

+0

停止了崩潰,但現在我對每個搜索都有無限循環。 – user1787130

1

對於初學者來說,如果搜索到的數字不在數組中,那麼Search中的主循環就沒有辦法了。

然後,您在使用high之前,它已被賦予任何值。

可能還有其他問題。你在開發它時如何測試?

+0

在Code :: Blocks 10.05中運行它 – user1787130