-4

How can I find max value of array using pointers? I must use cpp+header combo and [] is not allowed. Here is a part of the code.

main.cpp

const int NUMBERS = 30;

int main() {

int array[NUMBERS] = { 1, 3, 6, 9 };
sort(array, array + NUMBERS);

...

std::cout << max_v1(array, NUMBERS) << std::endl;
std::cout << max_v2(array, array + NUMBERS) << std::endl;
}

I got arrays.cpp and under it:

int max_v1(int *ptr, int size)
{
    //TODO
}

int max_v2(int *firstptr, int *lastptr)
{
    //TODO
}
Justin
  • 24,288
  • 12
  • 92
  • 142
4uvak91
  • 15
  • 4

1 Answers1

0

Here is a little diagram to help you.

Array pointer to first element:

|1|3|6|9|
 ^
 ptr

Dereferencing to get value:

*ptr == 1

Array pointer + size (points past the last element):

|1|3|6|9|
         ^
         ptr + size

Array pointer to last element:

|1|3|6|9|
       ^
       ptr + size - 1

Dereferencing to get the value:

*(ptr + size - 1) == 9

Therefore the function 1 should look like this:

int max_v1(int *ptr, int size)
{
    return *(ptr + size - 1);
}

Would you be able to do the second function by yourself?

P.S. Make sure NUMBERS you pass as second argument is equal to the actual size of the array, or it won't work (for obvious reasons demonstrated above)

Killzone Kid
  • 6,171
  • 3
  • 17
  • 37
  • Perhaps I'm misreading the OP, but I believe by "max" he means the largest element in the array, not the item at the location of the largest index (but I could be wrong). Regardless though, I like your visualization of pointers with the array! – scohe001 Mar 12 '18 at 19:29
  • 1
    @scohe001: A sorted array has the largest element at the final position. – IInspectable Mar 12 '18 at 19:31
  • @scohe001 OP is using default `std::sort` to sort the array prior calling both functions, so it is safe to assume the array will be sorted and the last element will be greatest. – Killzone Kid Mar 12 '18 at 19:31
  • Yea I'm looking for largest element, but this helps a lot too. Very helpful. – 4uvak91 Mar 12 '18 at 19:31
  • Ahhh I completely missed that. Oops! – scohe001 Mar 12 '18 at 19:33
  • @KillzoneKid how can I iterate then if the array is not sorted? – 4uvak91 Mar 12 '18 at 21:27
  • Same way, the only difference sorting makes is that you do not need to check every element but go straight to the end. Otherwise you have to make a loop and check and compare each element of the array. – Killzone Kid Mar 12 '18 at 22:02