在C编程中,您可以将整个数组传递给函数。在学习之前,让我们先看看如何将数组的单个元素传递给函数。
传递单个数组元素
将数组元素传递给函数与将变量传递给函数类似。
示例1:传递单个数组元素
#include <stdio.h>
void display(int age1, int age2) {
printf("%d\n", age1);
printf("%d\n", age2);
}
int main() {
int ageArray[] = {2, 8, 4, 12};
// pass second and third elements to display()
display(ageArray[1], ageArray[2]);
return 0;
}
输出
8 4
在这里,我们以与传递变量给函数相同的方式,将数组参数传递给了display()
函数。
// pass second and third elements to display()
display(ageArray[1], ageArray[2]);
我们可以在函数定义中看到这一点,其中函数参数是单个变量
void display(int age1, int age2) {
// code
}
示例2:将数组传递给函数
// Program to calculate the sum of array elements by passing to a function
#include <stdio.h>
float calculateSum(float num[]);
int main() {
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};
// num array is passed to calculateSum()
result = calculateSum(num);
printf("Result = %.2f", result);
return 0;
}
float calculateSum(float num[]) {
float sum = 0.0;
for (int i = 0; i < 6; ++i) {
sum += num[i];
}
return sum;
}
输出
Result = 162.50
要将整个数组传递给函数,只需要将数组名作为参数传递。
result = calculateSum(num);
但是,请注意函数定义中[]
的使用。
float calculateSum(float num[]) {
... ..
}
这会告知编译器您正在将一个一维数组传递给函数。
将多维数组传递给函数
要将多维数组传递给函数,只需要将数组名传递给函数(与一维数组类似)。
示例3:传递二维数组
#include <stdio.h>
void displayNumbers(int num[2][2]);
int main() {
int num[2][2];
printf("Enter 4 numbers:\n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
scanf("%d", &num[i][j]);
}
}
// pass multi-dimensional array to a function
displayNumbers(num);
return 0;
}
void displayNumbers(int num[2][2]) {
printf("Displaying:\n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
printf("%d\n", num[i][j]);
}
}
}
输出
Enter 4 numbers: 2 3 4 5 Displaying: 2 3 4 5
注意函数原型和函数定义中的参数int num[2][2]
// function prototype
void displayNumbers(int num[2][2]);
这表示该函数接受一个二维数组作为参数。我们也可以将多于2维的数组作为函数参数传递。
在传递二维数组时,不必指定数组的行数。但是,应始终指定列数。
例如,
void displayNumbers(int num[][2]) {
// code
}
推荐阅读:C中的按引用调用