1、为什么要使用结构体?
为了表示一些复杂的事物,而普通的基本类型无法满足。
2、结构体定义:
把一些基本类型数据组合在一起形成一个新的复合数据类型。
3、结构体是一种类型:
int类型、char类型、float类型、结构体类型...。
4、如何定义一个结构体
struct Student //定义结构体注意没有定义变量(struct Student类型)
{
int age;
float score;
char sex;
};
5、定义结构体类型变量
struct Student st = {80,66.6,'F'}; //定义了结构体变量st,并赋值。
6、结构体变量的第二种定义方法
struct Student2
{
int age;
float score;
char sex;
}st2;//定义结构体类型变量st2;
缺点:只能定义1个变量st2;
7、结构体的第三种定义方式(比较少用)
struct
{
int age;
float score;
char sex;
};
8、结构体的赋值和初始化
# include <stdio.h>
struct Student //定义结构体注意没有定义变量 "结构体类型"是类型
{
int age;
float score;
char sex;
};
int main()
{
struct Student st = {80,66.6F,'F'}; //定义了结构体变量,并赋值;
struct Student st2; //定义第二个结构体变量;
struct Student *pst = &st; //定义结构体类型的指针pst,注意这里不能写成st;
st2.age = 10;
st2.score = 88.6F; //88.6默认是doubie类型,后加“f”或“F”表示88.6为float类型,任何一个数想要变更成float型都可以用这个方法;
st2.sex = 'F';
printf("%d %.1f %c\n",st.age,st.score,st.sex);//取出变量
printf("%d %.1f %c\n",st2.age,st2.score,st2.sex);
printf("%d %.1f %c\n",pst->age,pst->score,pst->sex); //pst->age 在计算机内部转化为(*pst).age
return 0;
}
9、对pst->age的理解
1) pst->age 在计算机内部转化为(*pst).age 这是一种硬性规定,也是“->”的含义;
2) 所以 pst->age 等价于 (*pst).age 也等价于 st.age;
3) 即pst->age 等价于 st.age 因为 pst->age 是被转化为 (*pst).age来执行的
pst->age 的含义;
4) pst所指向的那个结构体变量中的age这个成员;
10、结构体函数
#include <stdio.h>
#include <string.h>
struct Student
{
int age;
char sex;
char name[100];
};
void OutputStudent(struct Student ss);
void InputStudent(struct Student *pstu);
/* void InputStudent(struct Student stu) //形参stu 当函数运行到InputStudent()时,形参被修改,运行完之后被释放,但不会改变st的值。
{
st.age = 10;
st.sex = 'F';
strcopy(st.name "小敏"); //不能写成stu.name = "张三"
}*/
int main(void)
{
struct Student st;
//InputStudent(st);//实参 (错误示范)
InputStudent(&st);
OutputStudent(st);
return 0;
}
/** void InputStudent(struct Student stu) //形参stu 当函数运行到InputStudent()时,形参被修改,运行完之后被释放,但不会改变st的值。
{
st.age = 10;
st.sex = 'F';
strcopy(st.name "小敏"); //不能写成stu.name = "张三"
}*/
void OutputStudent(struct Student ss)//输出是直接将st的赋给ss所以用指针或直接赋值都可以;
{
printf("%d %c %s\n",ss.age,ss.sex ,ss.name);
}
void InputStudent(struct Student *pstu)//pstu只占4个字节,因为指针总是指向第一个地址;
{
(*pstu).age = 10;
strcpy(pstu->name,"张三");
pstu->sex = 'F';
}