I'm trying to write a template function that utilizes the length of the array, given just the reference. I know the following code works
template <unsigned S>
void outputArray(int (&a)[S]) {
// S = length of array
}
int main() {
int a[6] = {0};
outputArray(a);
}
I am now attempting to expand upon this by using a dynamically allocated array. I'm pretty sure this isn't possible given that the size of the array in the previous case was determined at compile time, but I could be wrong.
void readFile(int*) {
int a_temp[MAX_DATA]; // MAX_DATA is predefined constant
int length;
// a_temp and length assigned from file
a = new int[length];
memcpy(a, &a_temp, sizeof(int)*length);
}
template <unsigned S>
void outputArray(int (&a)[S]) {}
int main() {
int* a;
readFile(a);
outputArray(a); // This is where my problem lies --- Mismatched types
}
Of course the irrelevant logic is truncated. As you can see in the readFile function, I am reading a variable length array from a file. However, I have no idea how to pass the array to the outputArray function as type int [S]
using the pointer.
I am restricted to using arrays (no C++ vectors) because this is a homework assignment. If there is absolutely no way for me to pass the pointer as a type int [S]
then I will go down the route of simply having the readFile function return the value of the length of the array.