为什么需要结构体
为了表示一些复杂的事物,而普通的基本数据类型无法满足实际的需求。
什么叫结构体
把一些基本类型数据组合在一起形成的一个新的复合数据类型,叫做结构体。
结构体的定义
一般有三种方式,但是这里只介绍第一种,因为其他两种并不常用。
注:这里只是定义了一个新的数据类型,并未定义变量
struct Student{
int id;
int score;
char sex;
};
赋值和初始化
- 定义的同时给可以整体赋值
- 如果定义完之后,则只能单个的赋初始值
结构体变量的运算
结构体变量不能相加,不能相减,不能互相乘除。
但结构体变量可以互相赋值。
sturuct Student stu1, stu2;
stu1*stu2 stu1 + stu2 ...错误
stu1 = stu2 或 stu2 = stu1 正确
如何取出结构体变量中的每一个成员
第一种方式:
结构体变量名.成员变量
第二种方式:
指针变量名- >成员变量名
指针变量名- >成员变量名 在计算机内部会被转换为(*指针变量名).成员变量名的方式来执行,所以说这两种方式是等价的。
pst ->id 的含义:
pst 所指向的那个结构体变量中的id成员变量。
#include<stdio.h>
#include<string.h>
typedef struct Student{
int id;
int score;
char sex;
}ST;
int main(){
ST st1;
ST st2;
// 第一种取成员变量的方式 结构体变量名.成员变量
st1.id = 1;
st1.score = 100;
st1.sex = 'F';
// 第二种取成员变量的方式 指针变量名->成员变量名
struct Student * pst; // 定义一个指针变量
pst = &st2; //让指针变量指向结构体变量st2
pst->id = 2;
pst->score = 59;
pst->sex = 'M';
printf("%d %d %c\n", st1.id, st1.score, st1.sex);
printf("%d %d %c", st2.id, st2.score, st2.sex);
return 0;
}
第二种方式在计算机内部都会转换为第一种方式,第二种方式是一种硬性规定。
所以 pst->id等价于 (*pst).id 也等价于 st2.id
在数据结构中一般都会用到第二种,所以这里需要重点掌握第二种方式。
结构体变量和结构体变量指针作为函数参数传递的问题
要在函数内部对其成员变量进行修改,需要传递指针!!
推荐使用结构体指针变量做传递。
#include<stdio.h>
#include<string.h>
/*
通过结构体完成对结构体的输入和输出
*/
void OutputStudent(struct Student pstu);
void InputStudent(struct Student *pstu);
struct Student{
int age;
char name[50];
char sex;
};
int main(){
struct Student st;
InputStudent(&st);
OutputStudent(st);
return 0;
}
/*
//本函数无法修改主函数的值,所以本函数是错误的
void InputStudent(struct Student stu){
stu.age = 10;
strcpy(stu.name, "张三"); // 不能写成 stu.name = "张三"
stu.sex = 'M';
}
*/
void InputStudent(struct Student *pstu){ //pstu本身只占4个字节
pstu->age = 10;
strcpy(pstu->name, "张三"); // 不能写成 stu.name = "张三"
pstu->sex = 'M';
}
//内部不需要修改值,用不用指针都行
// !!! 但是推荐指针,因为指针占用内存更少,速度更快。
void OutputStudent(struct Student pstu){
printf("%d %s % c", pstu.age, pstu.name, pstu.sex);
}
当函数不需要对其内部的成员变量修改时,是传递指针好呢?还是传递变量好呢?
传递指针好!!!
指针的优点:
- 快速的传递数据
- 耗用内存更小
- 执行速度更快