傳遞數組參數,其核心就是傳遞該數組的首地址。然后函數再通過數組、指針等,用該數組的首地址構造一個新的數組或指針,再通過傳遞過來的數組大小,對該數組進行操作。
#include <stdio.h>
#define SIZE 4
int sumbyarr(int a[],int n);
int sumbypointer(int *p,int n);
int sumbyaddress(int address,int n);
int sumbypointer2(int *begin,int *end)
int main(void)
{
int arr[SIZE]={10,20,30,40};
int sum1;
//使用數組作為形參接收數組
sum1=sumbyarr(arr,SIZE);
printf("the total of the arr by array is:%d\n",sum1);
//使用指針作為形參接收數組
int sum2;
sum2=sumbypointer(arr,SIZE);
printf("the total of the arr by pointer is:%d\n",sum2);
//使用地址作為形參接收數組
int sum3;
sum3=sumbyaddress(arr,SIZE);
printf("the total of the arr by address is:%d\n",sum3);
//使用兩個指針形參接收
int sum4;
sum4=sumbypointer2(arr,arr+SIZE);
printf("the total of the arr by pointer2 is:%d\n",sum4);
getchar();
return 0;
}
int sumbyarr(int a[],int n)
{
int index;
int total=0;
for(index=0;index<n;index++)
{
total+=a[index];
}
return total;
}
int sumbypointer(int *p,int n)
{
int index;
int total=0;
for(index=0;index<n;index++,p++)
{
total+=*p;
}
return total;
}
int sumbyaddress(int address,int n)
{
int *p=address;
int index;
int total=0;
for(index=0;index<n;index++,p++)
{
total+=*p;
}
return total;
}
int sumbypointer2(int *begin,int *end)
{
int total=0;
while(begin<end)
{
total+=*begin;
begin++;
}
return total;
}
以上代碼演示怎樣定義有數組作為參數的函數。
如果數組作為參數傳遞進入某個函數,并且在這個函數中改變了數組元素的值,那么程序返回后,這個數組元素的值有沒有改變呢?
當然,值改變了,因為數組是通過地址傳遞的,改變了被調函數中數組的值也就意味著同時改變了主調函數中數組的值。因為它們的地址是相同的。