I made a for loop for searching and sorting in the header file. Both loops start off like this:

for (int i = 0; i < n ; i++)

find.c compiles fine for me but when I put the needle at the end of the array, it doesn't work. But it works fine if the needle is at the top or in the middle of a sorted or unsorted array. Can someone please lead me to the right direction?

Thank you.

  • 1
    test your search and sort functions separately, if you are using binary search, then what condition have you placed 'values[mid] == value' to get the exact element, if yes then try 'values[mid] == value || values[mid+1] == value'.
    – sinister
    Commented Aug 18, 2014 at 2:38

1 Answer 1


Without seeing your code, my guess would be that your for loop is stopping 1 short of actually evaluating the last item. You could change your middle parameter of your for loop to: i <= n to test for this possibility.

  • My guess would be that doing this will most likely induce a segfault (out of bounds access) =P
    – abelinux
    Commented Dec 19, 2014 at 19:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .