如何在 C 语言中将整个数组作为参数传递给函数?

cserver side programmingprogramming更新于 2025/5/15 13:07:17

数组

数组是一组使用通用名称存储的相关元素。以下是将数组作为参数传递给函数的两种方法 −

  • 将整个数组作为参数传递给函数
  • 将单个元素作为参数传递给函数

将整个数组作为参数传递给函数

  • 要将整个数组作为参数传递,只需在函数调用中发送数组名称即可。

  • 要接收数组,必须在函数头中声明它。

示例 1

#include<stdio.h>
main (){
   void display (int a[5]);
   int a[5], i;
   clrscr();
   printf ("enter 5 elements");
   for (i=0; i<5; i++)
      scanf("%d", &a[i]);
   display (a); //调用数组
   getch( );
}
void display (int a[5]){
   int i;
   printf ("elements of the array are");
   for (i=0; i<5; i++)
      printf("%d ", a[i]);
}

输出

Enter 5 elements
10 20 30 40 50
Elements of the array are
10 20 30 40 50

示例 2

让我们考虑另一个例子来了解有关将整个数组作为参数传递给函数的更多信息 −

#include<stdio.h>
main (){
   void number(int a[5]);
   int a[5], i;
   printf ("enter 5 elements
");    for (i=0; i<5; i++)       scanf("%d", &a[i]);    number(a); //调用数组    getch( ); } void number(int a[5]){    int i;    printf ("elements of the array are
");    for (i=0; i<5; i++)       printf("%d
" , a[i]); }

输出

enter 5 elements
100
200
300
400
500
elements of the array are
100
200
300
400
500

相关文章