Pointers

closed account (G3AqfSEw)
Write a function find_min that takes a double pointer indicating the start of an array, and an int indicating the length of the array. It should return a pointer to the minimum number in the array.
You can assume there are no ties.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
using namespace std;

double* find_min(double* a, int n) {
???? WHAT GOES HERE???
}

int main() {
   int n;
   cin >> n;
   double arr[100];
   for (int i=0; i<n; i++) cin >> arr[i];

   // call your function and save result
   double* min_loc = find_min(arr, n);
   
   cout << ...;    // there is some hidden testing code here
   cout << "Pointed-to value is " << *min_loc << endl;

   // change that variable to 1000
   *min_loc = 1000;
   // run your code again
   min_loc = find_min(arr, n);
   
   cout << ...;    // there is some hidden testing code here
   cout << "Pointed-to value is " << *min_loc << endl;
}
you have to find the smallest value and return a pointer to it.

the algorithm to find it is generally:
1) set variable v to first array location.
2) iterate over all in array. if smaller than v, set v to new one.
3) here, you also need to update a pointer each time you update v. Or, you can only track the pointer, and dereference it each compare. your choice.

closed account (G3AqfSEw)
double *p_min = a;
for(double *i = a + 1; i< &a[n]; i++)
{
*p_min=*a;
}

like this?
no, not quite.

double *min = &array[0];
for(int I = 1; I < arraysize; I++)
{
if (array[I] < min[0])
min = &array[I];
}

I see what you are trying to do, and you *can* do it inside the for loop body but its very convoluted to do it. The above is the straightforward readable way. In yours, n isn't changing, and the comparison being done is for the loop termination not the test needed for each array element, its not correct.

you can do this..

for(double*min = &array[0], int I = 1; I < arraysize; min = min[0] > array[I] ? &array[I] : min, I++);

if I got all that correct from typing it in here without checking it. Something like that, anyway, its not any better and its a bit of a struggle to grok.



Last edited on
Topic archived. No new replies allowed.