如何在 C 語言中將整個陣列作為引數傳遞給函式?


陣列

陣列是儲存於共同名稱下的一組相關項。以下兩種方式可將陣列作為引數傳遞給函式−

  • 將整個陣列作為引數傳送給函式
  • 將單個元素作為引數傳送給函式

將整個陣列作為引數傳送給函式

  • 要將整個陣列作為引數傳送,只需在函式呼叫中傳送陣列名稱。

  • 要接收陣列,必須在函式頭中宣告該陣列。

示例 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); //calling array
   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); //calling array    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

更新於:2021 年 3 月 9 日

972 次瀏覽

開啟你的事業

透過完成課程獲得證書

開始吧
廣告
© . All rights reserved.