函数参数为数组

一维数组

函数定义

函数定义时有四种方式:
方式一:

void testfunc(int a[], int size)

方式二:

void testfunc(int* a, int size)

方式三:

void testfunc(int a[10], int size)

方式四:

template<class T>
void testfunc(T a, int size)

方式五:

template<class T>
void testfunc(T& a, int size)

前四种方式,在函数中,a的类型都是int*,sizeof(a)都是4,即一个指针的字节数;第三种方式中,[]中的数其实可以随便填,不会报错说超出数组范围,类型是int*,sizeof(a)是4,且第三种方式一般不要用,而应当将数组长度以参数传入。第五种方式的类型是int [5](假设传入的实参是长度为5的int数组),sizeof(a)是5*4=20.
以上所有定义方式中,在函数中对形参的数组进行修改,都会改变实参的数组。

函数调用

调用以数组为参数的函数时只有一种方式:

testfunc(a, size)

二维数组

函数定义

函数定义时有四种方式:
方式一:

void testfunc(int a[][3], int size0, int size1)

方式二:

void testfunc(int(*a)[3], int size0, int size1)

方式三:

template<class T>
void testfunc(T a, int size0, int size1)

方式四:

template<class T>
void testfunc(T& a, int size0, int size1)

前三种方式,在函数中,a的类型都是int(*)[3],sizeof(a)都是4,即一个指针的字节数;第四种方式的类型是int [2][3】(假设传入的实参是长度为【2】【3】的int数组),sizeof(a)是2x3x4=24.
注意,形参定义时一定要写列数,不用写行数。

函数调用

调用以数组为参数的函数时只有一种方式:

testfunc(a, size0, size1)
发布了52 篇原创文章 · 获赞 0 · 访问量 685

猜你喜欢

转载自blog.csdn.net/UniversityGrass/article/details/104679139
今日推荐