コードの問題は、配列に存在しない要素を検索した場合looker
に等しくなり、無効なlast
場所で配列要素にアクセスしようとすることです。last
代わりに、次のことができます。
bool seqSearch (int list[], int last, int target, int* locn) {
int looker;
for(looker=0;looker<last;looker++) {
// target found.
if(list[looker] == target) {
*locn = looker; // copy location.
return true; // return true.
}
}
// target not found.
*locn = -1; // copy an invalid location.
return false; // return false.
}
次のように関数を呼び出します。
int list[] = {5,4,3,2,1}; // the array to search in.
int size = sizeof(list)/sizeof(list[0]); // number of elements in the array.
int target = 3; // the key to search for.
int locn; // to hold the location of the key found..and -1 if not found.
if( seqSearch(list,size,target,&locn) ) {
// target found in list at location locn.
} else {
// target not found in list.
}