C语言之结构体类型

为什么需要结构体

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

代码示例

# include <stdio.h>
struct Student
{
	int age;
	float score;
	char sex;
};

int main(void)
{
	struct Student st = {80, 66.6, 'F'};	
/*	int age;
	float score;
	char sex;
	int age2;
	float score2;
	char sex2;
*/
	return 0;
}

结构体

定义结构体方式

# include <stdio.h>

//第一种方式
struct Student
{
	int age;
	float score;
	char sex;
};

//第二种方式
struct Student2
{
	int age;
	float score;
	char sex;
} st2;

//第三种方式
struct 
{
	int age;
	float score;
	char sex;
} st3;

int main(void)
{
	struct Student st = {80, 66.6, 'F'};	

	return 0;
}

使用结构体

1、赋值和初始化

  • 定义的同时可以整体赋值。
  • 如果定义完之后,则只能单个赋初值。

2.如果取出结构体变量中的每一个成员

  • 结构体变量名.成员名

  • 指针变量名->成员名 (更常用) 它会在计算机内部转化成 (* 指针变量名).成员名 的方式来执行,所以两者是等价的。

取出结构体变量成员

# include <stdio.h>

//第一种方式
struct Student
{
	int age;
	float score;
	char sex;
};

int main(void)
{
    /*
    1、 pst->age 会在计算机内部转化成 (*pst).age的方式来执行,这就是->的含义。
    2、 所以 pst->age 等价于  (*pst).age 也等价于 st.age
    3、 pst->的含义:pst 所指向的那个结构体变量中的age这个成员。
    */
	struct Student st = {80, 66.6F, 'F'}; //初始化  定义的同时赋初值
	struct Student * pst = &st;  //&st不能改成st

	st.score = 66.6f; //如果希望一个实数是float类型,则必须在末尾加f或F.
	pst->age = 88;//第二种方式
	printf("%d %f
", st.age, pst->score);	

	return 0;
}

注意

结构体变量的大小略大于其内部成员类型所占字节数之和。

若想通过函数对主函数结构体变量进行修改,则主函数必须发送地址,外函数定义指针结构体变量,通过外函数内部语句完成对变量的修改。而仅想输出、读取操作,则不用传地址,定义指针过程。

发送地址

/*
    发送地址还是发送内容
	目的:指针的优点之一:快速的传递数据,耗用内存小执行速度快
*/
# 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(void)
{
	struct Student st ; 
	//printf("%d
", sizeof(st));

	InputStudent(&st); //对结构体变量输入  必须发送st的地址
	OutputStudent(&st); //对结构体变量输出  

	return 0;
}

void OutputStudent(struct Student *pst)
{
	printf("%d %c %s
", pst->age, pst->sex, pst->name);
}

void InputStudent(struct Student * pstu) //pstu只占4个字节
{
	(*pstu).age = 10;
	strcpy(pstu->name, "张三");
	pstu->sex = 'F';	
}
原文地址:https://www.cnblogs.com/Guard9/p/12905126.html