为什么 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.