I'm trying to pass this array by reference but my code doesn't seem to be able to pick up the function. Help?
#include <iostream>
using namespace std;
void print( int (&array)[], int lower_bound, int upper_bound );
int main()
{
// generate array
const int SIZE = 20;
int array[SIZE];
for ( int i = 0; i < SIZE; i ++ ) array[i] = rand()%500;
// end generate array
print(array,0,19);
return 0;
}
void print( int (&array)[], int lower_bound, int upper_bound )
{
for ( int i = lower_bound; i <= upper_bound; i ++ ) cout << i << " : " << array[i] << endl;
}
How to pass an array by reference in CPP?
You almost got the right syntax, but you need the array's size, which you could specify explicitly if you only need to support one size:
const int SIZE = 20;
void print( int (&array)[SIZE], int lower_bound, int upper_bound );
or use a function template to deduce it if you need functions for different sizes:
template <size_t N>
void print( int (&array)[N], int lower_bound, int upper_bound )
{
// code here
}
Note that there are more idiomatic solutions in C++. One is to pass begin and one-past-the-end iterators (plain pointers will do) specifying the range. Others are to use std::array
for fixed size arrays and std::vector
for dynamically sized ones.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.