简体   繁体   中英

C++: Syntax of passing a pointer array through a function

So I have these 2 methods: the first is meant to take in 5 integer values, sum them up, then call the findLowest() method that returns the lowest found value, and subtracts that from the sum (then divides by 4 and prints results to screen).

I think the issue I'm having is the values it's returning are memory addresses. I've tried to understand how to dereference integers to get the value, but truth be told all of the online resources I've looked up have gone over my head.

Below is what I have so far:

void calcAverage(int* arr[5])
{
   int sum = 0;

   for (int a = 0; a < 5; a++)
      sum += *arr[a];

   sum -= findLowest(*arr);

   cout << "AVERAGE " << (sum / 4) << endl;
}


int findLowest(int* arr[5])
{
   int lowest = *arr[0];

   for (int a = 1; a < 5; a++)
   {
      if ((int)arr[a] < lowest)
         lowest = *arr[a];
   }


   return lowest;
}

On top of that, on the line that says

sum -=findLowest(*arr);

it pops up an error that reads

argument of type "int *" is incompatible with parameter of type "int **"

Thanks for the help in advance, and sorry if the post's a bit scattershot: I'm not really confident with this pointer/reference stuff to begin with.

You are almost there, but you should not dereference on this line:

sum -= findLowest(*arr);

Instead, just pass in the array, because that is what the function expects:

sum -= findLowest(arr);

Unrelated:

If you can, use a std::vector or std::array , the former for dynamically sized arrays, the latter for a compile time array. These both are safer, have more functions, and are easier to pass around.

Also use smart pointers for ownership of pointers instead of raw pointers. Smart pointers manage the ownership of an object so that you do not need to manually call new and delete .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM