同类型的结构体如何赋值 以及 结构体的值传递和地址传递的区别

同类型的结构体如何赋值 以及 结构体的值传递和地址传递的区别

同类型结构体变量赋值

#include <stdio.h>


struct Student
{
	int age;
	char name[50];
	int score;
};

int main(int argc, char const *argv[])
{
	int a = 10;
	int b;
	//1、把a的值给了b
	//2、a和b没有关系,两个变量都是独立的
	b = a;

	//1、相同类型的2个结构体变量可以相互赋值
	//2、尽管2个结构体变量的内容一样,但是2个变量是没有关系的独立内存
	struct Student s1 = {18, "mike", 70};
	struct Student s2;
	s2 = s1;
	printf("%d, %s, %d\n", s2.age, s2.name, s2.score);

	return 0;
}

在这里插入图片描述

值传递和地址传递区别

#include <stdio.h>

struct Student
{
	int age;
	char name[50];
	int score;
};

//值传递,效率低,这里只是打印tmp的值,不是真正去打印stu2的值
void fun(struct Student tmp)
{
	tmp.age = 22;
	printf("%d, %s, %d\n", tmp.age, tmp.name, tmp.score);
}

//地址传递,效率高,这里才是真正去打印stu2
void fun2(struct Student *p)
{
	printf("%d, %s, %d\n", p->age, p->name, p->score);
}

int main(int argc, char const *argv[])
{
	struct Student stu2 = {18, "mike", 59};

	//fun(s1);

	fun2(&s1);

	return 0;
}

结构体值传递示意图
在这里插入图片描述

结构体地址传递结构体
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/CCai_x/article/details/84074858