1.为什么需要结构体:
为了表示一些复杂的事物,而普通的基本类型无法满足,比如一个学生需要表示其姓名,年龄,学号。
结构体是一个复合数据类型。
2.如何定义结构体:
第一种:
struct Student
{
int age;
float score;
char sex[5];
};//分号不要忘
第二种:
struct Student
{
int age;
float score;
char sex[5];
}stu1;//定义了一个结构体类型的(变量),注意区别前面有typedef
**
typedef struct Student
{
int age;
float score;
char sex[5];
}stu1;//代表将结构体这个(类型名)重新命名为stu1,而没有定义变量;
第三种:
struct
{
int age;
float score;
char sex[5];
}stu1;
3.怎么使用结构体变量
赋值和初始化
struct Student
{
int age;
float score;
char sex[5];
};
int main()
{
//第一种
struct Student st1 = {80, 99.9, "boy"};
printf("%d %f %s ",st1.age,st1.score,st1.sex);
//第二种
struct Student st2;
st2.age = 80;
st2.score = 99.9f;//在C语言中默认99.9是double类型,若想以float类型输出,写成99.9f;
strcpy(st2.sex,"boy");//特别注意字符串赋值不能用st2.sex = boy;
printf("%d %f %s ",st2.age,st2.score,st2.sex);
//第三种
struct Student st3;
struct Student *pst = &st3;
pst->age = 88;
pst->score = 99.9f;
strcpy(pst->sex,"boy");
printf("%d %f %s ",st3->age,st3->score,st3->sex);
}
结构体变量的输入输出:
//结构体变量输入必须发送变量st的地址,因为要改变值只能用指针
void InputStudent(struct Student * pstu)
{
(*pstu). age = 10;
strcpy(pstu->name,"xuwei");
strcpy(pstu->sex,"boy");
}
//结构体变量输出可以发送地址也可直接输出,因为输出不需要改变值,所以指针可用可不用
但为了节省内存,提高运行速度,推荐发送地址
void Out putStudent(struct Student ss)
{
printf("%d %c %s\n", ss. age, ss. sex, ss. name) ;
}
int main(void)
{
struct Student st;
InputStudent (&st); //对结构体变量输入
Out putStudent(st); //对结构体变量输出
return 0;
}
结构体变量的运算:
结构体变量之间不能加减乘除,但可以相互赋值,如: st1 = st2;是对的