int *find(int *arr, int numElemns, int *value)
{
for (int i =0; i < numElemns; i++) // function to find an element in an array using linear search
{
if (arr[i] == *value)
{
return &arr[i];
}
}
return NULL;
}
I'm kind of new to pointers and it's a bit confusing. If I wanted to return a pointer to value, how would I do it?
would the definition be like this? int *find(int *arr, int numElemns, int *value)
How would I go from there?
At line 8, either return arr+i; or return &arr[i];
Note: You probably want to move line 12 to after line 14, otherwise you're going to exit the loop on the first comparison, regardless of the number of elements.
The convention for the not found condition with pointers is: return NULL;
Should work just fine, what exactly is the problem?
EDIT: Just going to ask, have you tried printing the return value? (I would say to dereference it first but you'd need to check if it's null or not before that to avoid exceptions).
int *createArray(int &size) // function to create a dynamic array of random elements
{
int *array1;
array1 = newint[size];
srand(time(0));
for (int i = 0; i < size; i++)
{
array1[i] = rand() % 20;
}
return array1;
}
int *find(int *arr, int size, int *value)
{
for (int i =0; i < size; i++) // function to find an element in an array using linear search
{
if (arr[i] == *value)
{
return &arr[i];
}
}
return NULL;
}
int main()
{
int *numbers;
int arraysize = 0;
int integer = 0;
cout << "please enter an array size: ";
cin >> arraysize;
cout << endl << endl;
numbers = createArray(arraysize);
cout << "The elements of the array are: ";
for (int i = 0; i < arraysize; i++)
{
cout << numbers[i] << " ";
}
cout << endl << endl;
cout << "enter an integer: ";
cin >> integer;
cout << endl << endl;
find(numbers, arraysize, &integer);
system("pause");
return 0;
}
When I call the function find, it displays nothing. Thanks again.