0

In the following program

#include <iostream>

bool contains ( int * sarr, size_t n, int i ) // checks whether the integer i is in the sorted array sarr of length n
{ 

    int * pa = sarr; int * pb = sarr + n;
    if (pa == pb) return false; // empty array
    --pb;
    while (pa != pb)
    {
        if (*pa == i || *pb == i) return true;
        int * pc = (pa + pb)/2;
        if (*pc < i)
            pa = pc;
        else 
            pb = pc;
    }
    if (*pa == i || *pb == i)
       return true;
    else 
       return false;
}


int main () 
{
    int arr [] = {1, 1, 6, 10, 19, 22, 22, 22, 50};
    std::cout << contains(arr, sizeof(arr)/sizeof(int), 6); // should print 1
    return 0;
} 

I'm getting the compiler error

error: invalid operands of types 'int*' and 'int*' to binary 'operator+'

on the line

int * pc = (pa + pb)/2;

Why is that? I thought it was perfectly valid to add pointers. Or do I need to perform some casts on the right side?

How can I make that algorithm more compact and efficient while continuing to cover all the corner cases?

Also, I'm tagging this as both C and C++ because it's C-style C++.

1 Answers1

3

It is not valid to add pointers. It is valid to add integer values to pointers (offsets). You can work around that by using (pb - pa) / 2 + pa. Subtracting pointers gives you the size of the range.

wilx
  • 17,697
  • 6
  • 59
  • 114