结构体的传参为什么优先选择传地址?

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/flf1234567898/article/details/101979638

结构体与函数结合
结构体传参数时有两种传参数方式,传值 传地址
我们在编写程序时优先考虑哪一种呢?
我们来看下面一个例子

#define _CRT_SECURE_NO_WARNINGS 1

#include<stdio.h>
#include<Windows.h>

struct Change
{
	int x;
	int y;
};
struct Student
{
	char name[20];
	int age;
	struct Change s;
	struct Node *pointer;
};

void Print(struct Student s)
{
	printf("%s", s.name);
}
void Print1(struct Student *j)
{
	printf("%d", j->age);
}

int main()
{
	struct Student n = { "范龙飞",18,{6,8},NULL };
	Print(n);
	Print1(&n);
	system("pause");
	return 0;
}

我们发现 2种实现的效果是一样的,真的如此吗?
函数的实参传给形参实际上是形参对于实参的临时拷贝
如果结构体比较大并且成员很多的话,会大大地浪费空间和时间,而传地址恰好能够完美的解决这点,因此当遇到函数传参数问题时,优先选择传地址。

猜你喜欢

转载自blog.csdn.net/flf1234567898/article/details/101979638