Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

จะส่งผ่านแต่ละองค์ประกอบในอาร์เรย์เป็นอาร์กิวเมนต์เพื่อทำงานในภาษา C ได้อย่างไร


หากแต่ละองค์ประกอบถูกส่งผ่านเป็นอาร์กิวเมนต์ จะต้องกำหนดองค์ประกอบอาร์เรย์พร้อมกับตัวห้อยในการเรียกใช้ฟังก์ชัน

ในการรับองค์ประกอบ จะใช้ตัวแปรอย่างง่ายในการกำหนดฟังก์ชัน

ตัวอย่างที่ 1

#include<stdio.h>
main (){
   void display (int, int);
   int a[5], i;
   clrscr();
   printf (“enter 5 elements”);
   for (i=0; i<5; i++)
      scanf("%d", &a[i]);
   display (a [0], a[4]); //calling function with individual arguments
   getch( );
}
void display (int a, int b){ //called function with individual arguments
   print f ("first element = %d",a);
   printf ("last element = %d",b);
}

ผลลัพธ์

Enter 5 elements
   10    20    30    40    50
First element = 10
Last element = 50

ตัวอย่างที่ 2

ลองพิจารณาอีกตัวอย่างหนึ่งสำหรับการส่งองค์ประกอบแต่ละรายการเป็นอาร์กิวเมนต์ไปยังฟังก์ชัน

#include<stdio.h>
main (){
   void arguments(int,int);
   int a[10], i;
   printf ("enter 6 elements:\n");
   for (i=0; i<6; i++)
      scanf("%d", &a[i]);
   arguments(a[0],a[5]); //calling function with individual arguments
   getch( );
}
void arguments(int a, int b){ //called function with individual arguments
   printf ("first element = %d\n",a);
   printf ("last element = %d\n",b);
}

ผลลัพธ์

enter 6 elements:
1
2
3
4
5
6
first element = 1
last element = 6