0

I was wondering if this is the proper way create a temporary array using pointers in a class. Part of my problem says this:

getMedian – returns the median value of the array. See Chapter 10 Programming Challenge 6 (p. 693) for a discussion of the term median. Taking the median will require a sorted array. You will need to create a temporary array to sort the values (to preserve the ordering of numbers). Do not sort the private member numbers array. Dynamically allocate/deallocate a temporary array in your getMedian function to determine the median.

My code:

double Statistics::getMedian() const
{
    int tempArray[length];

    for (int k = 0; k < length; k++){
        tempArray[k] = numbers[k];
    }

    bubbleSort(tempArray);

    return 0;
}

Before obviously doing the median part and a proper return statement, is this.

How you properly copy over a temporary array to alter for this problem? I don't think it is because I'm not properly allocating or deallocating anything, but I don't understand how to create a temporary array without altering the original.

1 Answers1

1

Your assignment says you are to allocate/deallocate the array dynamically. That means (in C++) using new and delete. Since you want an array, you should use array space allocator operators new[] and delete[].

double Statistics::getMedian() const
{
    int *tempArray = new int[length];

    for (int k = 0; k < length; k++){
        tempArray[k] = numbers[k];
    }

    // work with tempArray

    delete[] tempArray;

    return 0;  // or the median
}

EDIT: As suggested in the comment below, modern (C++11 and newer) way is to use smart pointers. That would mean your code could look like this.

#include <memory>

double Statistics::getMedian() const
{
    std::unique_ptr<int[]> tempArray (new int[length]);

    for (int k = 0; k < length; k++){
        tempArray[k] = numbers[k];
    }

    // work with tempArray like you would with an old pointer

    return 0;  // or the median
    // no delete[], the array will deallocate automatically
}

Check unique_ptr template class for more details. Note that this solution might not be what your professor wants, especially when the assignment talks about deallocation.

Community
  • 1
  • 1
Honza Remeš
  • 1,193
  • 8
  • 11
  • Worth adding in a comment about using smart pointers to guard the pointer from unexpected departure from the function without hitting the `delete`. – user4581301 Apr 08 '16 at 23:32