数组类型的参数做函数入参,会退化为指针。函数内,再通过sizeof求大小,就是指针的大小了。
32位系统,指针大小4;64位系统,指针大小8;
解决方法:可以通过引用的方式,传入入参,这样可以防止入参退化为指针。
#include <iostream>
using namespace std;
typedef unsigned char BYTE;
typedef BYTE STRINGLIST[20]; 定义 STRINGLIST 新的变量类型,或者说是给 BYTE STRINGLIST[20] 起了一个别名。
//退化为指针
void printInputParameter1(BYTE stringList[])
{
cout << "---- 退化 : " << sizeof(stringList) << endl;
}
//退化为指针
void printInputParameter2(BYTE *stringList)
{
cout << "---- 退化 : " << sizeof(stringList) << endl;
}
//退化为指针
void printInputParameter3(STRINGLIST stringList)
{
cout << "---- 退化 : " << sizeof(stringList) << endl;
}
//通过引用的方式,防止了退化
void printInputParameter4(STRINGLIST &stringList)
{
cout << "---- 未发生退化 : " << sizeof(stringList) << endl;
}
//指针退化学习
int main(int argc, char *argv[])
{
BYTE stringList[20] = "helloworld";
cout << "------- 1 : " << sizeof(stringList) << endl;
printInputParameter1(stringList);
printInputParameter2(stringList);
STRINGLIST stringArrayList = {'H','E','L','L','O'};
cout << "------- 2 : " << sizeof(stringArrayList) << endl;
printInputParameter3(stringArrayList);
printInputParameter4(stringArrayList);
system("pause");
return EXIT_SUCCESS;
}
执行结果: