Searching through an array

So i have a function thats supposed to go through an array and look for a ID stored in that array, and if its not found itll send back -1.
the problem is , whenever i have like 2 or 3 items in the array, and i ask to look for the 1st or 2nd item in the array, it says its not in there and sends back -1 but when i ask for the last item in the array it will send it back. Im confused as to why it sends me back -1 when im looking for anything but the last item in the array.

1
2
3
4
5
6
7
8
9
10
11
12
13
int find(string *id, int count, string num)
{       
        int i, pos; 
        for(i=0; i < count; i++){
                if(*(id+i) == num){                                            
                        pos=i;
                 }        
                else     
                         pos=-1;                        
        }                                               
        return pos;
}
if you don't return once you find the correct value the cycle proceeds and unless the last value is what you are looking for you are in the else branch of the if construct.
Try

1
2
3
4
5
6
//your code
if(*(id+i) == num){                                            
                        pos=i;
return pos;
                 }
//your code         


of course this code will not handle multiple entries of the same id.
Ohh i get it! that code works. Thanks alot!
Topic archived. No new replies allowed.