普通数组传递
#include <iostream>
using namespace std;
void get_size(int a[5])
{
std::cout << sizeof(a) << std::endl;
for(int i = 0; i < 5; i++)
std::cout<<a[i]<<std::endl;
}
int main()
{
int a[5] = { 1, 2, 3, 4, 5};
get_size(a);
return 0;
}
/* ouput
4
*/
在X86架构下,它的结果是4,就是一个指针的大小,通过验证,它确实是一个指针
证明
1.传入比指定参数数组容量大的数组
#include <iostream>
using namespace std;
void get_size(int a[5])
{
std::cout << sizeof(a) << std::endl;
for(int i = 0; i < 6; i++)
std::cout<<a[i]<<std::endl;
}
int main()
{
int a[6] = { 1, 2, 3, 4, 5, 6};
get_size(a);
return 0;
}
是可以传进去并且是可以访问到a[5]的
2.把参数改成指针形式
#include <iostream>
using namespace std;
void get_size(int *a)
{
std::cout << sizeof(a) << std::endl;
for(int i = 0; i < 6; i++)
std::cout<<a[i]<<std::endl;
}
int main()
{
int a[6] = { 1, 2, 3, 4, 5, 6};
get_size(a);
return 0;
}
程序正常运行
数组的引用方式进行传递
#include <iostream>
using namespace std;
void get_size(int (&a)[5])
{
std::cout << sizeof(a) << std::endl;
}
int main()
{
int a[5] = { 1, 2, 3, 4, 5};
get_size(a);
return 0;
}
/* ouput
20
*/
用引用的时候我们发现,算出来的字节数就是这个数组占的字节数了,这样的好处是什么,就是你可以通过sizeof(a) / sizeof(int) 算出这个数组的容量是多少。
这样的话,就必须传入指定大小的数组了。那怎么传不定大小的数组呢
非模板参数的数组引用
#include <iostream>
using namespace std;
template<short count>
void get_size(int(&array)[count])
{
std::cout << sizeof(array) << std::endl;
}
int main()
{
int a[6] = { 1, 2, 3, 4, 5, 6 };
get_size(a);
}
这样就可以既传递了数组的大小,又可以改变数组大小的值。