Talk About Network



Register and Login
Nick
Password
Register create new account Sign up is FREE and you can post replies, new topics, bookmark posts and more!
Recover lost password


Programming > C > Problems with a...
Latest [ Topics | Posts ] Archive Post A New Topic Post a Reply
<< Topic < Post Post 1 of 4 Topic 26132 of 26198
Post > Topic >>

Problems with a simple linear search

by nembo kid <nembo@[EMAIL PROTECTED] > May 9, 2008 at 05:31 PM

I have an issue with a simple function that has to make a linear search 
for a key into an array.

If the key is found in the array, the function it has to return 1 to the 
caller and pass array index through a out parameter.

The issue is that the out parameter is not being updated.

If I return the position to the caller (instead to use a out parameter) 
all is ok.

But I would to use a boolean (1 or 0) value as return value to the 
caller: 1 stays for found, 0 stays for not found.

Thanks in advance and apologies for my bad english.

Here it is my piece of code.

/*** Code starts here ***/

/* Search for number 'x' in array v[] */
/* If 'x' found pass array position through 'pos' parameter */
/* and returns 1 to caller; else returns 0 */

int linsearch (int v[], int nmax, int x, int pos)
{

    int i;

    for (i=0; i<nmax; i++)
    {
       if(v[i]==x)
       {
          pos=i;    /* pass the index where found */
          return 1; /* returns 1 (found) */
       }
    }

    return 0; /* Exit from for...so returns 0 */
}

int main (void)
{
     int myvet[] = {5,4,3,2,1};

     int key = 2; /* Number to find */

     int index=0; /* Actual parameter that holds index of element */

     if(linsearch(myvet, 5, 2, index))		
	printf ("\nNumber %d found at position %d ", key, index);
     else
         printf ("\nNumber %d not found", key);

    return 0;
}

/*** Code ends here ***/




 4 Posts in Topic:
Problems with a simple linear search
nembo kid <nembo@[EMAI  2008-05-09 17:31:14 
Re: Problems with a simple linear search
"Jim Langston"   2008-05-09 08:40:21 
Re: Problems with a simple linear search
nembo kid <nembo@[EMAI  2008-05-09 18:01:57 
Re: Problems with a simple linear search
Eric Sosman <esosman@[  2008-05-09 11:41:28 

Post A Reply:
  Go here to Signup

AddThis Feed Button


About - Advertising - Contact - Frequently Asked Questions - Privacy Policy - Terms of Use - Signup

Contact
tan12V112 Tue May 13 21:39:04 CDT 2008.