Am I using pointers and array correctly?

advertisements

My teacher for an assignment problems requires that we pass an array to a function that just finds the median of it. and if there's an even amount of numbers, it averages the two in the middle. I quote from him "use pointers whenever possible". The only one I could see using a pointer is the array itself?

I understand the concept of what needs to happen, I'm just not sure how to properly use pointers and Googling doesn't reveal too helpful results.

int medianArray(int *pArray, int sizeArray)
{
    if(sizeArray % 2 == 1)
    {
        return (pArray[((int)(sizeArray/2)) -1 ] + pArray[((int)(sizeArray/2)) +1 ]) / 2;
    }
    else
        return pArray[(int) sizeArray/2];
}


You've got the right idea here, but you're computing your offsets wrong.

Here's an idea:

size_t median = sizeArray / 2;

return (pArray[median] + pArray[median+1]) / 2;

Don't forget this will fail if the values exceed int bounds, and additionally you should be using size_t to express sizes as that should never be negative.

Additionally, there's no point in casting the result of an int calculation to int.

Regarding this C++ lesson, I think anything that bucks the principles laid out in the Standard Library better have a good reason for doing so. While an academic exploration of the benefits of pointers vs. iterators vs. references is always encouraged, advocating pointers "whenever possible" is a bad plan and comes from a C mindset.

In a modern C++ course this assignment would revolve around computing the median of an unsorted Standard Library container of an arbitrary type by defining a template function.