为什么需要结构体
首先我们对比数组,数组是元素类型一样的数据集合,如果希望数据的类型不同,这时候就需要结构体了。
例如学生信息。
如何定义结构体
struct Student // 一般结构体要求大写开头
{
int num;
char name[32];
char sex;
int age;
double score;
char addr[32];
}; // 这里的分号一定不能忘
上面算是一个模板,一般不需要赋具体的值。
在声明的同时,定义变量,尽量少用。
struct Student
{
int num;
char name[32];
char sex;
int age;
double score;
char addr[32];
} student1, student2;
应该如何定义变量呢?
#include <stdio.h>
#include <string.h>
int main()
{
// int a = 10
// 可以把 struct Student 看成是 int
struct Student stu1;
stu1.num = 1;
stu1.age = 10;
stu1.score = 98.5;
strcpy(stu1.name, "hello");
strcpy(stu1.addr, "广州");
struct Student stu2 = {2, "张三", 'g', 17, 99.5, "北京"};
}
如何输入元素呢?
printf("学号:%d,年龄:%d,分数:%1f,姓名:%s,地址:%s\n",
stu2.num, stu2.age, stu2.score, stu2.name, stu2.addr);