this question has answer here:
i aware array can passed function in quite few ways.
#include <iostream> #include <utility> using namespace std; pair<int, int> problem1(int a[]); int main() { int a[] = { 10, 7, 3, 5, 8, 2, 9 }; pair<int, int> p = problem1(a); cout << "max =" << p.first << endl; cout << "min =" << p.second << endl; getchar(); return 0; } pair<int,int> problem1(int a[]) { int max = a[0], min = a[0], n = sizeof(a) / sizeof(int); (int = 1; < n; i++) { if (a[i]>max) { max = a[i]; } if (a[i] < min) { min = a[i]; } } return make_pair(max,min); } my code above passes first element while should passing array (or technically, pointer array) , hence, output 10, 10 both max , min (i.e. a[0] only).
what doing wrong, guess correct way.
the contents of array being passed function. problem is:
n = sizeof(a) / sizeof(int) does not give size of array. once pass array function can't size again.
since aren't using dynamic array can use std::array remember size.
you use:
template <int n> void problem1(int (&a) [n]) { int size = n; //... }
Comments
Post a Comment