與您的代碼的問題是,如果你尋找不存在的數組中的元素,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.
}
我知道我需要傳遞數組和最後一個數組的大小,但我不知道要在target和int中放置什麼* locn – shinjuo 2010-05-04 06:18:46