I'm trying to take an arbitrary-length array into a function (bubble sort used here as an example)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
void bubblesort(int (&listy)[]){
int length = (sizeof(listy)/sizeof(*listy));
bool sorted = false;
int holder;
int tail;
while (!sorted){
sorted = true;
tail = 1;
for(int c = 0; c < (length-tail); c++){
if(listy[c] < listy[c+1]){
sorted = false;
holder = listy[c];
listy[c] = listy[c+1];
listy[c+1] = holder;
}
}
}
}
But it fails to compile with
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
In file included from sorttest.cpp:1:0:
sort.h:1:31: error: parameter 'listy' includes reference to array of unknown bound 'int []'void bubblesort(int (&listy)[]){
^
sort.h: In function 'void bubblesort(int (&)[])':
sort.h:2:29: error: invalid application of 'sizeof' to incomplete type 'int []'int length = (sizeof(listy)/sizeof(*listy));
^
sorttest.cpp: In function 'int main()':
sorttest.cpp:6:17: error: invalid initialization of reference of type 'int (&)[]' from expression of type 'int [10]'
bubblesort(moo);
^
In file included from sorttest.cpp:1:0:
sort.h:1:6: error: in passing argument 1 of 'void bubblesort(int (&)[])'void bubblesort(int (&listy)[]){
^
The length of the array is part of the array type so you can't leave it out when passing the array by reference. What you could do is passing a pointer to the first element in the array:
void bubblesort(int listy[]){
or
void bubblesort(int* listy){
(Even if they look different both ways are exactly the same)
You can get the array reference approach to work if you make the function a template (with the length as a parameter.) But:
1. the int[] plus length approach makes more sense if you're going to have lots of different sizes of array, as the template based approach will result in different versions of the function being instantiated.
2. the template based approach will only work with actual arrays; it cannot be used with dynamically allocated arrays.