First off, what do you mean by this:
>...to find what spot a certain number in an array is.
What do you mean by "spot"? You can either have the element index number, or the memory address (in the form of a pointer).
Your code is getting confused between the two.
Here is your code with the necessary fixes. I have provided two versions, one which return a pointer to the int, and one which returns an index element number.
Code:
#include <iostream.h>
/* This version returns a pointer to the int in question
* If not found, NULL is returned.
*/
int *Search(int NUM_ELEMENTS, int arr[], int searchele)
{
for (int i = 0; i < NUM_ELEMENTS; i++)
{
if (arr[i] == searchele) return(&arr[i]);
}
return(NULL);
}
int main(void)
{
int arr[] = { 1, 2, 5, 4 };
int *temp;
temp = Search(4, arr, 5);
if (temp)
cout << "Found "<<*temp <<" at memory address " << temp <<endl;
else
cout << "Not found" <<endl;
return(0);
}
Code:
#include <iostream.h>
/* This version returns an int which is the index within the array.
* If not found, -1 is returned.
*/
int Search(int NUM_ELEMENTS, int arr[], int searchele)
{
for (int i = 0; i < NUM_ELEMENTS; i++)
{
if (arr[i] == searchele) return(i);
}
return(-1);
}
int main(void)
{
int arr[] = { 1, 2, 5, 4 };
int temp;
temp = Search(4, arr, 5);
if (temp >= 0)
cout << "Found "<<5 <<" at index " << temp <<endl;
else
cout << "Not found" <<endl;
return(0);
}
>return(0); // Should be return 0;
return (0); is valid.
>Multiple returns are bad ideas in general...
No, I don't believe they are. Depending on their usage, multiple returns are a good thing, as shown in the above example.