我收到的時候第一recursice呼叫犯了一個錯誤,該錯誤:C++通過遞歸二進制搜索
Unhandled exception at 0x002A2E44 in rekBinSearch.exe: 0xC0000005: Access violation reading location 0x0000000A.
它的原因是:
if ((*pEnd - pBegin) == 0) / There's only one element */
看來,當我設置新的開始和結束地址,我做錯了什麼,因爲這些無法在遞歸調用中讀取。他們被「套」的:
find(x, (int*)pBegin, pMid);
全碼:
bool find(const int x, const int* pBegin, const int* pEnd)
{
if ((*pEnd - *pBegin) == 0) /* There's only one element */
{
if (x == (int)pEnd) /* That element could be the correct one */
return true;
else /* If it is not then return false, x is not in the array */
return false;
}
int *pMid = (int*)(pEnd - pBegin); /* pMid should be the adress to the element in the middle of the array */
if (x >= (int)pMid) /* If x is in array it is to the right of the middle */
find(x, (int*)pMid, pEnd);
else /* If x is in array it is to the left of the middle */
find(x, (int*)pBegin, pMid);
}// find
什麼我做錯了什麼或如何我在想錯了嗎?謝謝我推進。
擺脫所有這些演員陣容,我懷疑你會中途解決問題。 – davmac
'(pEnd-pBegin)'不計算中點,但是指針之間的元素數量。也許有0x0A元素? –
類似語法的迭代器的習慣用法是處理開始和結束的相等性以指示空的間隔。你的函數沒有檢測到傳入一個空數組。 – jxh