原文: https://beginnersbook.com/2014/01/c-passing-array-to-function-example/
就像变量一样,数组也可以作为参数传递给函数。在本指南中,我们将学习如何使用按值调用和按引用调用方法将数组传递给函数。
要理解本指南,您应该具有以下 C 编程主题的知识:
使用按值调用方法将数组传递给函数
正如我们在这种类型的函数调用中已经知道的那样,实际参数被复制到形式参数中。
#include <stdio.h>void disp( char ch){printf("%c ", ch);}int main(){char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};for (int x=0; x<10; x++){/* I’m passing each element one by one using subscript*/disp (arr[x]);}return 0;}
输出:
a b c d e f g h i j
使用按引用调用将数组传递给函数
当我们在调用函数的同时传递数组的地址,然后这就是按引用函数调用。当我们传递一个地址作为参数时,函数声明应该有一个指针作为接收传递地址的参数。
#include <stdio.h>void disp( int *num){printf("%d ", *num);}int main(){int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};for (int i=0; i<10; i++){/* Passing addresses of array elements*/disp (&arr[i]);}return 0;}
输出:
1 2 3 4 5 6 7 8 9 0
如何将整个数组作为参数传递给函数?
在上面的例子中,我们在 C 中使用for循环逐个传递每个数组元素的地址。但是,您也可以将整个数组传递给这样的函数:
注意:数组名称本身是该数组的第一个元素的地址。例如,如果数组名称为
arr,则可以说arr等同于&arr[0]。
#include <stdio.h>void myfuncn( int *var1, int var2){/* The pointer var1 is pointing to the first element of* the array and the var2 is the size of the array. In the* loop we are incrementing pointer so that it points to* the next element of the array on each increment.**/for(int x=0; x<var2; x++){printf("Value of var_arr[%d] is: %d \n", x, *var1);/*increment pointer for next element fetch*/var1++;}}int main(){int var_arr[] = {11, 22, 33, 44, 55, 66, 77};myfuncn(var_arr, 7);return 0;}
输出:
Value of var_arr[0] is: 11Value of var_arr[1] is: 22Value of var_arr[2] is: 33Value of var_arr[3] is: 44Value of var_arr[4] is: 55Value of var_arr[5] is: 66Value of var_arr[6] is: 77
