1.使用标准库规范
int sum_array( const int *beg, int *en ) { int sum = 0; while ( beg != en ) { sum += *beg++; } return sum; } int main() { int a[] = { 1,1,2,3,4,5,6,7,8,9 }; cout << sum_array( a, a + sizeof(a)/sizeof(*a) ); return 0; }
2.显式传递表示数组大小形参
int sum_array( const int *a, int size ) { int sum = 0; for ( int i = 0; i < size; i++ ) { sum += *(a + i); } return sum; } int main() { int a[] = { 1,1,2,3,4,5,6,7,8,9 }; cout << sum_array( a, sizeof(a)/sizeof(*a) ); return 0; }
3.数组大小 int sum_array( const int a[], int size ) { int sum = 0; for ( int i = 0; i < size; i++ ) { sum += *(a + i); } return sum; } int main() { int a[] = { 1,1,2,3,4,5,6,7,8,9 }; cout << sum_array( a, sizeof(a)/sizeof(*a) ); return 0; }