編寫一個程序,初始化一個double數組,然後把數組內容復制到另外兩個數組(3個數組都需要在主程序中聲明)。制作第一份拷貝的函數使用數組符號。制作第二份拷貝的函數使用指針符號,並使用指針的增量操作。把目標數組名和要復制的元素數目做為參數傳遞給函數。也就是說,如果給定了下列聲明,函數調用應該如下面所示:
double source [5]={1.1, 2.2, 3.3, 4.4, 5.5};
double targetl[5];
double target2 [5];
copy_arr (source, target1, 5);
copy_ptr (source, target1,5);
1 #include <stdio.h>
2
3 void copy_arr(double s[],double tar[],int c);
4 void copy_ptr(double *s,double *tar,int c);
5
6 int main(void){
7 double s[5]={1.1, 2.2, 3.3, 4.4, 5.5};
8 double t1[5],t2[5];
9 copy_arr(s,t1,5);
10 copy_ptr(s,t2,5);
11 int i;
12 printf("t1\t\tt2\n");
13 for(i=0;i<5;i++)
14 {
15 printf("t1[%d]=%.1f\t",i,t1[i]);
16 printf("t2[%d]=%.1f\n",i,t2[i]);
17 }
18 return 0;
19 }
20
21 void copy_arr(double s[],double tar[],int c){
22 int i;
23 for(i=0;i<c;i++){
24 tar[i]=s[i];
25 }
26 }
27
28 void copy_ptr(double *s,double *tar,int c){
29 int i;
30 for(i=0;i<c;i++){
31 *(tar+i)=*(s+i);
32 }
33 }
在函數定義部分也可以使用增量運算符:
1 void copy_arr(double s[],double tar[],int c){
2 int i=0;
3 while(i<c)tar[i]=s[i++];
4 }
5
6 void copy_ptr(double *s,double *tar,int c){
7 int i=0;
8 while(i<c)*(tar+i)=*(s+i++);
9 }