(struct)结构体变量作为函数参数调用的方法小结

(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);
    
}
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值