结构体

一、为什么需要结构体?

为了表示一些复杂的事物,而普通的基本类型无法满足实际要求

二、什么叫结构体?

把一些基本类型数据组合在一起形成的一个新的复合数据类型,这个叫做结构体

三、如何定义结构体?

struct 名字
{
内容
}

还有两种定义方法,不过不推荐:

struct 名字
{
内容
}变量名;
struct 
{
内容
}变量名;

四、结构的初始化

#include <malloc.h>

struct Student
{
	int age;
	char sex;
};

int main() {
	struct Student st = { 12,'m' };//第一种
	
	struct Student st2;//第二种
	st2.age = 12;
	st2.sex = 'm';
	
	return 0;
}

五、如何取出结构体变量的每一个成员?

#include <malloc.h>

struct Student
{
	int age;
	char sex;
};

int main() {
	struct Student st = { 12, 'm'};
	
	st.age = 10;//第一种调用
	
	struct Student* pst = &st;//第二种调用
	pst->age = 12;
	
	
	return 0;
}
  • pst->age在计算机内部会被转化成(*pst).age,没有什么为什么,这就是->的含义,这也是一种硬性规定
    所以:
    pst->ago 等价于(*pst).age 也等价于st.age
  • pst->ago的含义:pst所指向的那个结构体变量中的age这个成员

通过函数对结构体输入输出

#include<stdio.h>
#include<string.h>

struct Student
{
	int age;
	char sex;
	char name[100];
};
void InputStudent(struct Student* );
void OutputStudent(struct Student *);

int main() {
	struct Student st;
	InputStudent(&st);
	OutputStudent(st);

	return 0;
}

void InputStudent(struct Student* pstu) { //对结构体变量输入必须发送st的地址
	(*pstu).age = 10;
	strcpy(pstu->name ,"张三");
	pstu->sex = 'f';
}

//void OutputStudent(struct Student st) {
//	printf("%d ,%c , %s", st.age, st.sex, st.name);
//}

void OutputStudent(struct Student *st) {
/*对结构体变量输出可以发送st的地址,也可以直接发送st的内容,但为了减少减少内存的耗费,也为了提高执行速度,推荐发送地址*/
	printf("%d ,%c , %s", st->age, st->sex, st->name);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值