You can only get the correct sizeof result if you pass the array by reference.
Code:
void printArray(int (&a)[4])
{
cout << "sizeof(testArray) in f-call: " << sizeof(a) << endl;
int lengte = sizeof(a) / sizeof(int);
cout << lengte;
for (int i = 0; i < lengte; ++i)
cout << a[i] << " ";
cout << endl;
}
Of course, this makes using sizeof rather pointless, because this function can only accept arrays of 4 integers and nothing else.
You could make that into a template:
Code:
template <std::size_t N>
void printArray(int (&a)[N])
{
cout << "sizeof(testArray) in f-call: " << sizeof(a) << endl;
int lengte = sizeof(a) / sizeof(int);
cout << lengte << '\n';
for (int i = 0; i < lengte; ++i)
cout << a[i] << " ";
cout << endl;
}
which would still make sizeof pointless, because now you'd already know how many items there are.
Or you could use a real array class (to be added to the C++ standard library).
Code:
#include <iostream>
#include <boost/array.hpp>
using namespace std;
template <class Container>
void printArray(const Container& c)
{
for (int i = 0; i < c.size(); ++i)
cout << c[i] << " ";
cout << endl;
}
int main(int argc, char *argv[])
{
boost::array<int, 4> testArray = {2, 1, 2, 3};
printArray(testArray);
//mergeSort(testArray);
return 0;
}