# C Primer Plus 第10章 数组和指针 10.4 函数、数组和指针

2016/07/28 07:01

totao = sum(marbles);  // 可能的函数调用

int sum(int *ar);  //相就的原型

``````int sum(int *ar)    //相应定义
{
int i;
int total = 0;

for (i=0;i<10;i++)    //假设有10个元素
total+=ar[i];     //ar[i]与*(ar+i)相同
}``````

``````int sum(int *ar,int n)    //更通用的方法
{
int i;
int total = 0;

for (i=0;i<n;i++)    //使用n表示元素的个数
total+=ar[i];     //ar[i]与*(ar+i)相同
}``````

int sum(int ar[],int n);

``````//sum_arr1.c --对一个数组的所有元素求和
//如果不能使用%zd,请使用%u或%lu
#include <stdio.h>
#define SIZE 10
int sum(int ar[],int n);
int main(void)
{
int marbles[SIZE] = {20,10,5,39,4,16,19,26,31,20};
printf("The total number of marbles is %ld.\n",answer);
printf("The size of marbles is %lu bytes.\n",sizeof marbles);
return 0;
}
int sum(int ar[],int n)
{
int i;
int total=0;
for(i=0;i<n;i++)
total+=ar[i];
printf("The size of ar is %lu bytes.\n",sizeof ar);

}
``````

``````The size of ar is 4 bytes.
The total number of marbles is 190.
The size of marbles is 40 bytes.``````

10.4.1  使用指针参数

``````//sum_arr1.c --对一个数组的所有元素求和
//如果不能使用%zd,请使用%u或%lu
#include <stdio.h>
#define SIZE 10
int sump(int * start,int * end);
int main(void)
{
int marbles[SIZE] = {20,10,5,39,4,16,19,26,31,20};
printf("The total number of marbles is %ld.\n",answer);
return 0;
}
/*使用指针算术*/
int sump(int * start,int * end)
{

int total=0;
while(start < end)
{
total+=*start;  /*把值累加到total上*/
start++;        /*把指针向前推进到下一个元素*/
}
}
``````

for(i=0;i<n;i++)

while(start < end)

sump(marbles,marbles+SIZE);

total+=*start++ ;

``````/*order.c  --指针运算的优先级*/
#include <stdio.h>
int data[2]={100,200};
int moredata[2]={300,400};
int main(void)
{
int *p1,*p2,*p3;
p1=p2=data;
p3=moredata;
printf(" *p1=%d, *p2=%d, *p3=%d\n",*p1,*p2,*p3);
printf("*p1++ =%d, *++p2 =%d, (*p3)++ =%d\n",*p1++,*++p2,(*p3)++);
printf(" *p1 =%d,*p2 =%d,*p3 =%d\n",*p1,*p2,*p3);
return 0;
}
``````

``````  *p1=100, *p2=100, *p3=300
*p1++=100,*++p2=200,(*p3)++=300
*p1=200,*p2=200,*p3=301``````

10.4.2  评论：指针和数组

0
0 收藏

0 评论
0 收藏
0