数组参数
在 C++ 中,可以通过数组参数来传递数组给函数。这意味着你可以将一个数组作为函数的参数,以便在函数内部对数组进行操作或访问。
理解 C++ 中的数组参数涉及以下几个方面:
语法:在函数声明或定义中,可以使用数组类型作为参数类型。例如,void myFunction(int arr[]) 或 void myFunction(int arr[5])。这里的 arr 是一个形式参数,表示一个整数数组。
传递数组:当你调用带有数组参数的函数时,你可以传递一个数组作为实际参数。例如,int myArray[5] = {1, 2, 3, 4, 5}; myFunction(myArray);。在函数调用中,myArray 是一个实际参数,表示一个整数数组。
数组大小:在函数中,你可以使用数组参数来访问数组元素,并使用数组大小来遍历数组。在函数声明中,可以指定数组参数的大小,也可以省略大小。然而,在 C++ 中,数组参数的大小信息在函数内部是不可用的,因此通常需要额外的参数来传递数组的大小。
数组指针:在函数中,数组参数实际上是一个指向数组首元素的指针。因此,你可以使用指针算术或下标运算符来访问数组元素。例如,arr[0] 或 *(arr + 1)。
下面是一个示例函数,演示如何使用数组参数:
#include <iostream>
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
}
int main() {
int myArray[] = {1, 2, 3, 4, 5};
int size = sizeof(myArray) / sizeof(myArray[0]);
printArray(myArray, size);
return 0;
}
在这个示例中,printArray 函数接受一个整数数组 arr 和一个整数 size 作为参数。函数使用循环遍历数组,并打印每个元素。在 main 函数中,我们定义了一个整数数组 myArray,并计算数组的大小。然后,我们调用 printArray 函数,传递 myArray 和大小作为参数。
当你运行这个程序时,它会打印出数组的所有元素。
三种形式
void test1(int *s)
void test2(int s[])
void test3(int s[5])
实例
#include <iostream>
#include <vector>
using namespace std;
// 测试字符串和字符数组的参数传递
void test1(int *s){
cout<<*(s)<<endl;
return;
}
void test2(int s[]){
cout<<*s<<endl;
return;
}
void test3(int s[5]){
cout<<*s<<endl;
return;
}
int main()
{
int s1[]={1,2,3,4,5,6,7,8};
int s2[3]={4,5,6};
int* s3 = new int(999);
test1(s3);
test2(s3);
test3(s3);
return 0;
}
C++中数组参数的传递与处理

552

被折叠的 条评论
为什么被折叠?



