刘加加在成长(C++语言学习中)

学习、工作、生活,这是三个问题。

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  38 随笔 :: 0 文章 :: 24 评论 :: 0 Trackbacks

传递数组参数,其核心就是传递该数组的首地址。然后函数再通过数组、指针等,用该数组的首地址构造一个新的数组或指针,再通过传递过来的数组大小,对该数组进行操作。

#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;
}

以上代码演示怎样定义有数组作为参数的函数。
如果数组作为参数传递进入某个函数,并且在这个函数中改变了数组元素的值,那么程序返回后,这个数组元素的值有没有改变呢?

当然,值改变了,因为数组是通过地址传递的,改变了被调函数中数组的值也就意味着同时改变了主调函数中数组的值。因为它们的地址是相同的。
posted on 2008-05-16 23:54 刘加加 阅读(1359) 评论(0)  编辑 收藏 引用 所属分类: 学习C语言

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理