當函數具有特定大小的數組參數時,為什么要用指針替換它?根據下面的程序,#include <iostream>using namespace std;void foo( char a[100] ){
cout << "foo() " << sizeof( a ) << endl;}int main(){
char bar[100] = { 0 };
cout << "main() " << sizeof( bar ) << endl;
foo( bar );
return 0;}產出main() 100foo() 4為什么數組作為指向第一個元素的指針傳遞?這是C的遺產嗎?標準怎么說?為什么C+的嚴格類型安全性下降了?
3 回答

UYOU
TA貢獻1878條經驗 獲得超4個贊
boost
/std::tr1::array
/std::array
std::vector
?
template< std::size_t N >void f(char (&arr)[N]){ std::cout << sizeof(arr) << '\n';}

慕桂英546537
TA貢獻1848條經驗 獲得超10個贊
在C/C+術語中有一個很棒的詞,用于靜態數組和函數指針-衰變..考慮以下代碼:
int intArray[] = {1, 3, 5, 7, 11}; // static array of 5 ints
//...
void f(int a[]) {
// ...
}
// ...
f(intArray); // only pointer to the first array element is passed
int length = sizeof intArray/sizeof(int); // calculate intArray elements quantity (equals 5)
int ptrToIntSize = sizeof(*intArray); // calculate int * size on your system
- 3 回答
- 0 關注
- 788 瀏覽
添加回答
舉報
0/150
提交
取消