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

เหตุใด C จึงถือว่าพารามิเตอร์อาร์เรย์เป็นตัวชี้


C ถือว่าพารามิเตอร์อาร์เรย์เป็นตัวชี้ เนื่องจากใช้เวลาน้อยลงและมีประสิทธิภาพมากกว่า แม้ว่าเราสามารถส่งที่อยู่ของแต่ละองค์ประกอบของอาร์เรย์ไปยังฟังก์ชันเป็นอาร์กิวเมนต์ได้ แต่จะใช้เวลานานกว่า ดังนั้นจึงควรส่งต่อที่อยู่พื้นฐานขององค์ประกอบแรกไปยังฟังก์ชันเช่น:

void fun(int a[]) {
…
}
void fun(int *a) { //more efficient.
…..
}

นี่คือโค้ดตัวอย่างในภาษา C:

#include

void display1(int a[]) //printing the array content
{
   int i;
   printf("\nCurrent content of the array is: \n");
   for(i = 0; i < 5; i++)
      printf(" %d",a[i]);
}

void display2(int *a) //printing the array content
{
   int i;
   printf("\nCurrent content of the array is: \n");
   for(i = 0; i < 5; i++)
      printf(" %d",*(a+i));
}
int main()
{
   int a[5] = {4, 2, 7, 9, 6}; //initialization of array elements

   display1(a);
   display2(a);
   return 0;
}

เอาท์พุต

Current content of the array is:
4 2 7 9 6
Current content of the array is:
4 2 7 9 6