-1

This is the working code of something I've been working on while learning C++.
How could I modify this so that ArraySortToMedian() uses pointer notation instead of array notation to handle the array?

All my attempts so far haven't worked so there is something in the logical relation or the syntax that I am missing. Thank you in advance.

#include <iostream>
#include <fstream>

double ArraySortToMedian(int [], int ); 

using namespace std;

int main() 
{
    ifstream infile;
    infile.open("numbers.txt");

    const int SIZE = 6;
    int array[SIZE];
    int i = 0;
    double median;

    if(!infile)
    {
    cout << "couldn't find 'numbers.txt'";
    return 1;   
    }

    while(i < SIZE && infile >> array[i])
    i++;

    infile.close();

    for(i = 0; i < SIZE; i++)
    cout << *(array + i) << "!\n"; 

    median=ArraySortToMedian(array, SIZE);

    cout<< "\n" << median << "\n";
    return 0;
}

double ArraySortToMedian(int (x[]), int numElem)
{
    bool swap;
    int temp, i;
    double m;

    do
    {
    swap = false;
    for(i = 0;i < (numElem - 1); i++)
    {
        if( x[i] > x[i + 1] )
        {
            temp = x[i];
            x[i] = x[i + 1];
            x[i + 1] = temp;
            swap = true;
        }
    }
    }
    while (swap);
    cout << "\n";
    for(i = 0; i < numElem; i++)
    cout << x[i] << "\n";

    m = (x[numElem/2] + x[numElem/2]-1)/(double)2;
    return(m);
}
mrbw
  • 39
  • 5

2 Answers2

1

You could do this. However, i strongly advise against it, you're better off using std::array to get a much cleaner implementation. The syntax for such a function parameter is pretty ugly.

Using raw C-Arrays

template <size_t N>
double ArraySortToMedian(int (&x)[N], int numElement); 

Using STL array

template <size_t N>
double ArraySortToMedian(std::array<int,N>& x, int numElement)

This will not work with dynamically allocated arrays, if you try to overload these template to deal with pointers to arrays allocated with new it becomes exponentially more complicated.

Nowhere Man
  • 475
  • 3
  • 9
0

Just change the signature to int* arr and access the respected elements using *(x + i)

Dov Benyomin Sohacheski
  • 7,133
  • 7
  • 38
  • 64
  • This is the syntax for returning the median with reference notation that worked for me as of now : return (*(x + (numElem)/2)+*(x + (numElem-1)/2))/(double)2; What I was doing wrong was putting it like this: double FunctionName(int* arr[]) The [ ] were redundant for reference because arr is already pointing to its element first address. With experience I'll learn better practices and will make less syntax errors. Thank for helping me get there. – mrbw Apr 11 '16 at 02:43