soft_student soft_student - 3 months ago 7
C++ Question

Why is "2" always being returned from my function? Trying to find the index of a searched number within an array

I am trying to return the index of array if it matches a user defined number. I cant figure out why, no matter what I enter, the function returns "2".

#include <iostream>
using namespace std;
int search(int x, int *list);
int main()
{
int x;
int list[10] = { 20, 1, 18, 3, 16, 5, 14, 7, 12, 9};

cout << "Enter a number to search the list for: ";
cin >> x;
cout << endl;

cout << search(x, &list[10]) << endl;

system("PAUSE");
return 0;
}

int search(int x, int *list)
{
bool match = false;
for (int i = 0; i < 10; i++)
{
if (list[i] == x)
{
match = true;
}
if (match == true)
{
return i;
}
else if (match == false && i == 9)
{
return -1;
}
}
}

Answer

Because you have invoked undefined behavior by starting the search at index 10: search(x, &list[10]) should be search(x, list).

...and what's with that whole else if in the loop. Why not just return -1 at the end of the function. And why have a match variable - if a match is found just return i.

for (int i = 0; i < 10; i++)
{
    if (list[i] == x)
    {
        return i;
    }
}
return -1;