Please program to achieve the following functions: Write the function f() to achieve the sum of integer array elements.
#include<iostream>
using namespace std;
int f0(int a[],int size);
int f1(int *a,int size);
int main(){
int a[20],size,sum0,sum1;// size < 20
cin>>size;
for(int i=0;i<size;i++)
cin>>a[i];
sum0=f0(a,size);
sum1=f1(a,size);
cout<<sum0<<' '<<sum1<<endl;
return 0;
}
int f0(int a[],int size){
int sum=0;
for(int i=0;i<size;i++)
sum+=a[i];
return sum;
}
int f1(int *a,int size){
int sum=0;
for(int i=0;i<size;i++)
sum+=a[i];
return sum;
}
Test:
Here we have defined two functions, both of which have achieved the expected results. The a[] passed by the f0 function; the pointer of a passed by the f1 function. What does it mean? For a novice like me, I need to understand: that is to say, when a function calls an array as a parameter, it will only call its first address in order to improve efficiency. That is to say, the machine understands a[] as the first address of the entire array a, that is a的指针
, They are equivalent (the array name is a pointer), so there is no need to doubt that the first address of the array (array name) has the same effect as the array pointer. For a more in-depth understanding, I still need my continuous learning to make up for my shortcomings. Place!