我是一個新手,C++後,我寫程序來測試如何通過數組作爲函數的參數,我寫了這個小程序:C++:數組的大小已更改傳遞給函數
#include <iostream>
using namespace std;
void pass_by_array(int a[]) {
int a_len = sizeof(a);
int e_len = sizeof(a[0]);
cout << "size of array in func: " << a_len << endl;
cout << "size of element in func: " << e_len << endl;
}
int main() {
int foo[] = {1, 8, 2, 7, 3, 6};
int a_len = sizeof(foo);
int e_len = sizeof(foo[0]);
cout << "size of array in main: " << a_len << endl;
cout << "size of element in main: " << e_len << endl;
pass_by_array(foo);
return 0;
}
這裏的結果我得到:
size of array in main: 24
size of element in main: 4
size of array in func: 8
size of element in func: 4
所以到底是在那裏去?數組的大小改變了?!
在C和C++風格的數組上需要的一切:http://stackoverflow.com/q/4810664/1619294 –
看看http://stackoverflow.com/questions/1461432/what-is-array-decaying並查看接受的答案 –
您從未將數組大小傳遞給'pass_by_array',那麼它應該如何知道? (考慮'pass_by_array'是否在單獨的編譯單元中。) –