為什麼 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("
Current content of the array is:
");    for(i = 0; i < 5; i++)       printf(" %d",a[i]); } void display2(int *a) //printing the array content {    int i;    printf("
Current content of the array is:
");    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

更新於:2019 年 7 月 30 日

246 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.