C++:数组形参的传递

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dashumak/article/details/86487022

数组有两个特性:

  • 不允许拷贝:无法以值传递的方式使用数组形参
  • 使用数组时通常都会转换为指针:当我们为函数传递一个数组时,实际上传递的是指向数组首元素的指针。
  1. 传参的方法
    当下有一个数组int j[2]={0,1},我们自写了一个函数 void FindSomeOne(),要求将数组参数传进去。
    有以下两种方式(在函数内部使用时,Point++即可实现指针的移动)
  • void FindSomeOne(const int* Point)
  • void FindSomeOne(const int Point[])
    当我们使用此函数时这样写即可,FindSomeOne(j)

数组是以指针的形式传递给函数的,所以函数并不知道数组的确切尺寸,因此调用者应该为此提供一些信息,以防止使用时数组越界。最好的方法是使用标准库规范传参

void FindSomeOne(const int *beg,const int *end)
{
	while(beg!=end){
		cout<<*beg++<<endl;
	}
}

猜你喜欢

转载自blog.csdn.net/dashumak/article/details/86487022