数组名作为函数参数

数组名作为函数实参时,向形参(数组名或指针变量)传递的是数组首元素地址。

#include<stdio.h>
#include <windows.h>

float AverageScore(float arry[]);

int main(void)
{
    float Score[]={0};
    float AverNum=0;
    int i=0;

    printf("input 5 scores:\n");

    for(i=0;i<5;i++)
        scanf("%f",&Score[i]);
    printf("\n");

    AverNum=AverageScore(Score);

    printf("average score is %.2f\n",AverNum);

    system("pause");
    return 0;
}

float AverageScore(float arry[]) //分数平均值函数
{
    int i=0;
    float Aver=0;
    float Sum=0;
    float* p=NULL;

    p=arry;

    for(i=0;i<5;i++)
    {   
        Sum=Sum+p[i];
    }
        Aver=Sum/5;
        return(Aver);
}

运行结果:
这里写图片描述

程序分析:

用数组名作为函数的实参时,不是把数组元素的值传递至形参,而是把实参数组的说元素的地址传递给形参数组(上例中把Score[0]的地址传送给arry),这样两个数组(Score[]和arry[])就共指向一段内存空间,也就是说,形参数组中各个元素的值若发生变化就会使得实参数组元素的值发生变化。

以上。

参考资料:
1.谭浩强.C程序设计(第四版).北京:清华大学出版社,2010.

猜你喜欢

转载自blog.csdn.net/wangqingchuan92/article/details/78687783