结构体(结构传参方式的选择)

结构体

1、结构体类型的声明

结构体是一些值的集合,这些值称为成员变量,结果的每个成员可以是不同类型的变量

结构体的声明

struct	tag
{
	member-list
}variable-list;

例如:

#include <stdio.h>
#include <stdlib.h>

typedef struct Student 
{
	char name[20];//姓名
	int age;//年龄
	char sex[2];//性别
	char id[20];//学号
}Student;

int main()
{

	system("pause");
	return 0;
}

结构体成员的类型:

结构体成员可以死hi标量,数组,指针,或者其他结构体等.

2、结构体变量的定义和初始化

#include <stdio.h>
#include <stdlib.h>

struct Point 
{
	int x;
	int y;
}p1;//声明类型的同时定义变量p1

struct Point p2;//定义结构体变量p2

struct Point p3 = { 2, 3 };//定义今结构体变量p3并赋值

struct Stu 
{
	char name[20];
	int age;
};

struct Stu s = { "zhangsan", 20 };

struct Node 
{
	int data;
	struct Point p;
	struct Node* next;
}n1 = { 10, { 4, 5 }, NULL };//结构体嵌套初识化

struct Node n2 = { 20, { 5, 6 }, NULL };

int main()
{

	system("pause");
	return 0;
}

3、结构体成员访问

结构体通过点操作符来访问成员

#include <stdio.h>
#include <stdlib.h>

//结构体访问通过.操作符实现

struct Stu 
{
	char name[20];
	int age;
};

void Print(struct Stu *ps)
{
	printf("name = %s age = %d", (*ps).name, (*ps).age);
}

int main()
{
	struct Stu s = { "zhangsan", 20 };
	Print(&s);
	system("pause");
	return 0;
}

4、结构体传参

由于函数在传参的时候需要进行压栈操作,如果结构体过大,栈的开销过大,会导致性能下降的问题

因此结构体传参要传结构体地址

#include <stdio.h>
#include <stdlib.h>

struct Student1 
{
	int data[1000];
	int num;
};

struct Student1 s1 = { { 1, 2, 3, 4 }, 1000 };

//结构体传参
void Print1(struct Student1 s)
{
	printf("%d\n", s.num);
}

//结构体地址传参
void Print2(struct Student1 *ps)
{
	printf("%d\n", ps->num);
}

int main()
{
	Print1(s1);
	Print2(&s1);
	system("pause");
	return 0;
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值