傳遞數(shù)組參數(shù),其核心就是傳遞該數(shù)組的首地址。然后函數(shù)再通過(guò)數(shù)組、指針等,用該數(shù)組的首地址構(gòu)造一個(gè)新的數(shù)組或指針,再通過(guò)傳遞過(guò)來(lái)的數(shù)組大小,對(duì)該數(shù)組進(jìn)行操作。
#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;
//使用數(shù)組作為形參接收數(shù)組
sum1=sumbyarr(arr,SIZE);
printf("the total of the arr by array is:%d\n",sum1);
//使用指針作為形參接收數(shù)組
int sum2;
sum2=sumbypointer(arr,SIZE);
printf("the total of the arr by pointer is:%d\n",sum2);
//使用地址作為形參接收數(shù)組
int sum3;
sum3=sumbyaddress(arr,SIZE);
printf("the total of the arr by address is:%d\n",sum3);
//使用兩個(gè)指針形參接收
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;
}
以上代碼演示怎樣定義有數(shù)組作為參數(shù)的函數(shù)。
如果數(shù)組作為參數(shù)傳遞進(jìn)入某個(gè)函數(shù),并且在這個(gè)函數(shù)中改變了數(shù)組元素的值,那么程序返回后,這個(gè)數(shù)組元素的值有沒(méi)有改變呢?
當(dāng)然,值改變了,因?yàn)閿?shù)組是通過(guò)地址傳遞的,改變了被調(diào)函數(shù)中數(shù)組的值也就意味著同時(shí)改變了主調(diào)函數(shù)中數(shù)組的值。因?yàn)樗鼈兊牡刂肥窍嗤摹?