I receive an error when the first recursice call is made, the error:
Unhandled exception at 0x002A2E44 in rekBinSearch.exe: 0xC0000005: Access violation reading location 0x0000000A.
It is caused by:
if ((*pEnd - pBegin) == 0) / There's only one element */
It seems that that when i set the new start- and end-adress, i do something wrong since these can't be read on the recursive call. They are "set" by:
find(x, (int*)pBegin, pMid);
Full code:
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
What am I doing wrong or how am I thinking wrong?
(pEnd - pBegin)doesn't compute a midpoint, but the number of elements between the pointers. Perhaps there are 0x0A elements?