為什麼 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP