C语言学习笔记---结构体作为函数参数和返回值

  结构体不仅可以作为函数的参数传递,也可以作为函数的返回值。现在就分别来看一下这两种情况。

结构体作为参数

struct score
{
	int chinese;
	int math;
	int english;
};

int sum(struct score p)
{
	return (p.chinese + p.math + p.english);
}

int main()
{
	int total = 0;
	struct score s=
	{
		80,90,85
	};
	total = sum(s);
	printf("total is: %d \r\n",total);
	system("pause");
	return 0;
}

  定义一个结构体用于存储分数,然后使用sum()函数计算总分。将结构体作为参数传递给函数。这里的结构名不代表它的地址,而是结构体的值。上面的值传递方法相当下面这种操作:

struct names name1 = {“张”,“三”};
struct names name2 = name1;

  相当于将结构体name2直接初始化为结构体name1,它会将name1的每个成员值都赋给name2对应的成员。

  所以在上面的代码中将结构体作为参数传递,相当于在函数中又定义了一个结构体,传递的其实是结构体的备份。代码输出结果如下:
在这里插入图片描述
  在传递结构体本身的时候,属于值传递。所在在函数体内修改结构体的值时,不会改变函数体外结构体的值。比如修改代码如下:

struct score
{
	int chinese;
	int math;
	int english;
};

int sum(struct score p)
{
	p.chinese = 100;
	return (p.chinese + p.math + p.english);
}

int main()
{
	int total = 0;

	struct score s=
	{
		80,90,85
	};

	total = sum(s);

	printf("total is: %d \r\n",total);
	printf("chinese is: %d \r\n",s.chinese);

	system("pause");
	return 0;
}

  在sum()函数中修改了语文成绩,在mani()函数中打印完总分之后,继续打印一次语文成绩。

在这里插入图片描述
  通过输出结果可以看出,虽然总分成绩发生了改变,但是语文成绩其实没变。如果不想在函数中是成员的值被改变,那么在函数的参数中加上const 限定符。

int sum(const struct score p)
{
	return (p.chinese + p.math + p.english);
}

  此时在sum()函数中就不能修改成员的值。

结构体作为返回值

  函数的参数不仅可以是结构体,同样函数的返回值依然也可以是结构体。

struct score
	{
		int chinese;
		int math;
		int english;
	};
struct score get(void)
{
	struct score s;
	s.chinese = 80;
	s.math = 85;
	s.english = 70;
	return s;
}
int main()
{
	int total = 0;	
	struct score s1;	
	s1 = get();
	total = s1.chinese + s1.math + s1.english;
	printf("total is: %d \r\n",total);	
    printf("chinese: %d math: %d english: %d \r\n",s1.chinese,s1.math,s1.english);	
	system("pause");
	return 0;
}

  在get()函数中定义了一个结构体变量并给各个成员赋值,该函数的返回值是一个结构体。在主函数中也定义一个结构体,然后用它去接收函数返回的结构体。程序执行结果如下:
在这里插入图片描述
  通过输出的结果可以看到,主函数中结构体变量s1中各个成员的值和函数get()中设置的值一样。相当于在主函数中复制了一个结构体,在主函数中操作的结构体是函数中结构体的副本。此时如果在主函数中改变结构体成员的值,那么get()函数中的结构体是不受影响的。

  修改代码如下:

struct score
	{
		int chinese;
		int math;
		int english;
	};

struct score get(void)
{
	struct score s;
	s.chinese = 80;
	s.math = 85;
	s.english = 70;
	printf(" %d  %d  %d \r\n",s.chinese,s.math,s.english);
	return s;
}

int main()
{
	int total = 0;
	
	struct score s1;	
	s1 = get();
	total = s1.chinese + s1.math + s1.english;
	printf("total is: %d \r\n",total);
	printf("chinese: %d math: %d english: %d \r\n",s1.chinese,s1.math,s1.english);    
    s1.chinese = 100;
    get();	
	system("pause");
	return 0;
}

  第一次调用get()函数之后,将返回结构体的值打印出来,然后改变s1中chinese的值,接着再调用一次get()函数。

在这里插入图片描述

  通过输出结果可以看到,修改主函数中结构体成员的值并不影响get()函数中结构体成员的值。通过这种返回结构体的方法,传递的是原始数据的副本,可以有效的保护原始数据的安全性。

  • 11
    点赞
  • 50
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值