由於C/C++不像C#可直接從array身上取得array size,導致C/C++ developer須自己處理array size,以下是常見的幾種寫法。


1.在陣列尾端放一個特別的marker代表結束。C-Style string就是用這種技巧,如以下寫法。

1#include <iostream>
2
3using namespace std;
4
5void func(char *pia) {
6 while(*pia) {
7 cout << *pia++ << endl;
8 }
9}
10
11int main() {
12 char ia[] = {'a', 'b', 'c', '\0'};
13 func(ia);
14}

2.將陣列第一個元素和最後一個元素傳進去,STL的algorithm就是使用這個技巧,如sort(svec.begin(), svec.end());

1/**//*
2
4Filename : ArrayPassToFunctionSTL.cpp
5Compiler : Visual C++ 8.0 / ISO C++
6Description : Demo how to use pass array to function by STL convention
7Release : 01/03/2007 1.0
8*/
9
10#include <iostream>
11
12using namespace std;
13
14void func(const int *beg, const int *end) {
15 while(beg != end) {
16 cout << *beg++ << endl;
17 }
18}
19
20int main() {
21 int ia[] = {0, 1, 2};
22 func(ia, ia + 3);
23}

3.傳統C語言的做法,將array size當成參數傳進去

1/**//*
2
4Filename : ArrayPassToFunctionCStyle.cpp
5Compiler : Visual C++ 8.0 / ISO C++
6Description : Demo how to use pass array to function by C Style
7Release : 01/03/2007 1.0
8*/
9#include <iostream>
10
11using namespace std;
12
13void func(int *pia, size_t arr_size) {
14 for(size_t i = 0; i != arr_size; ++i) {
15 cout << pia[i] << endl;
16 }
17}
18
19int main() {
20 int ia[] = {0, 1, 2};
21 func(ia, 3);
22}

4.使用function template + refference array