💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 在 C 编程中将数组传递给函数 > 原文: [https://beginnersbook.com/2014/01/c-passing-array-to-function-example/](https://beginnersbook.com/2014/01/c-passing-array-to-function-example/) 就像变量一样,数组也可以作为参数传递给函数。在本指南中,我们将学习如何使用按值调用和按引用调用方法将数组传递给函数。 > 要理解本指南,您应该具有以下 [C 编程](https://beginnersbook.com/2014/01/c-tutorial-for-beginners-with-examples/)主题的知识: > > 1. [C - 数组](https://beginnersbook.com/2014/01/c-arrays-example/) > 2. [C 中的按值函数调用](https://beginnersbook.com/2014/01/c-function-call-by-value-example/) > 3. [C 中的按引用函数调用](https://beginnersbook.com/2014/01/c-function-call-by-reference-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; } ``` **输出:** ```c a b c d e f g h i j ``` ## 使用按引用调用将数组传递给函数 当我们在调用函数的同时传递数组的地址,然后这就是按引用函数调用。当我们传递一个地址作为参数时,函数声明应该有一个[指针](https://beginnersbook.com/2014/01/c-pointers/)作为接收传递地址的参数。 ```c #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; } ``` 输出: ```c 1 2 3 4 5 6 7 8 9 0 ``` ### 如何将整个数组作为参数传递给函数? 在上面的例子中,我们在 C 中使用[`for`循环](https://beginnersbook.com/2014/01/c-for-loop/)逐个传递每个数组元素的地址。但是,您也可以将整个数组传递给这样的函数: > 注意:数组名称本身是该数组的第一个元素的地址。例如,如果数组名称为`arr`,则可以说`arr`等同于`&arr[0]` 。 ```c #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; } ``` **输出:** ```c Value of var_arr[0] is: 11 Value of var_arr[1] is: 22 Value of var_arr[2] is: 33 Value of var_arr[3] is: 44 Value of var_arr[4] is: 55 Value of var_arr[5] is: 66 Value of var_arr[6] is: 77 ```