(struct)结构体变量作为函数参数调用的方法小结
https://blog.csdn.net/tham_/article/details/45370607
结构体变量、结构指针变量、结构数组作为函数的参数应用实例分析
struct stud
{
long int num;
float score;
};
/结构体变量作为函数的参数,修改之后的成员值不能返回到主调函数/
void funvr(struct stud t)
{
t.num=2000101;
t.score=71.0;
}
/结构体数组作为函数的参数,修改后的元素的成员值能返回到主调函数/
void funar(struct stud t[])
//void funar(struct stud &t)
{
t[0].num=3000101; /*注意结构体数组元素的成员的引用形式*/
t[0].score=81.0;
t[1].num=3000102;
t[1].score=82.0;
}
/结构体指针变量作为函数的参数,修改后的结构体成员的值能返回到主调函数/
void funpr(struct stud *t)
{
t->num=4000101; /*注意通过结构体指针变量引用成员的具体形式*/
(*t).score=92.0;
}
/在主函数中分别调用上述函数修改成员值,再验证结果的正确性/\
#include<stdio.h>
struct stud
{
long int num;
float score;
};
void funvr(struct stud t)
{
t.num=2000101;
t.score=71.0;
}
void funar(struct stud t[])
//void funar(struct stud &t)
{
t[0].num=3000101; /*注意结构体数组元素的成员的引用形式*/
t[0].score=81.0;
t[1].num=3000102;
t[1].score=82.0;
}
void funpr(struct stud *t)
{
t->num=4000101; /*注意通过结构体指针变量引用成员的具体形式*/
(*t).score=92.0;
}
void main()
{
struct stud a[2]={
{1000101,61.0}, {1000102,62.0}
};
struct stud b=a[0],*p;
printf("old b: b.num:%ld\tb.score:%f\n",b.num,b.score);
/*显示结构体变量b的成员的原有值*/
funvr(b);
/*验证第一种情况,观察并分析结果,看结构体变量作为函数参数时,形参结构体变量成员的值的改变能影响实参结构体变量的成员的值,
以下为输出调用函数funvr(b)之后的结果值*/
printf("call funvr() new b: b.num:%ld\tb.score:%f\n ",b.num,b.score);
funpr(&b); /*将结构体变量的指针对作为函数的参数*/
printf("call funpr() new b: b.num:%ld\tb.score:%f\n ",b.num,b.score);
/*输出结构体数组a元素的原来的成员值*/
printf("old a[0]:a[0].num:%ld\ta[0].score:%f\n ",a[0].num,a[0].score);
printf("old a[1]:a[1].num:%ld\ta[1].score:%f\n ",a[1].num,a[1].score);
/*将结构体数组a作为函数的参数,然后再输出其元素的成员的值,已经被修改了*/
funar(a);
printf(" new a[0]:a[0].num:%ld\ta[0].score:%f\n ",a[0].num,a[0].score);
printf("new a[1]:a[1].num:%ld\ta[1].score:%f\n ",a[1].num,a[1].score);
}