C语言 将数组传递给函数

来源:这里教程网 时间:2026-02-16 12:50:43 作者:

C语言 将数组传递给函数:就像变量一样,数组也可以作为参数传递给函数。在本指南中,我们将学习如何使用按值调用和按引用调用方法将数组传递给函数。

要理解本指南,您应该具有以下C 编程主题的知识:

    C – 数组C 中的按值函数调用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: 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 

相关推荐