一、问题描述
将数组传递给函数的时候,数组会退化成指针。
二、解决方法
#include "iostream"
#include "string"
#include "vector"
using namespace std;
//以指针接受数组时产生Array Decay
void test01(int *p) {
cout << sizeof(p) << endl;
}
//此种形式依旧不能解决数组退化
void test02(int (*p)[]) {
cout << sizeof(p) << endl;
}
//使用数组引用接受数组参数,避免Array Decay问题,但是需要指定数组引用的大小,否则不能通过编译
void test03(int (&p)[10]) {
cout << sizeof(p) << endl;
}
int main() {
int a[10] = {0};
test01(a);
test02(&a);
test03(a);
system("pause");
return 0;
}
程序输出
8 //test01输出
8 //test02输出
40 //test03输出