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

ทำไม C ถือ array parameters ว่าเป็น pointers


C ถือ array parameter เป็น pointers เพราะ less time consuming และ more efficient ถ้าส่ง address ของแต่ละ element ไปเป็น argument จะ time consuming มากกว่า ดีกว่าส่ง base address ของ first element:

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; }

Output

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