#include <stdio.h>
#include <string.h>
// 1. 定义一个结构体(先定义结构体再声明变量)
struct Student
{
int no;
char *name;
char sex;
float score;
};
// 2. 在定义结构体类型的同时声明结构体变量
struct Teacher
{
int no;
char *name;
float salary;
} t1, t2;
// 3. 定义结构体直接声明结构体变量, 没有结构体类型名
struct
{
char *plate_no; // 车牌号
char *brand; // 品牌
float price; // 售价
} car1, car2;
// 4. 通过 typedef 定义结构体
// typedef 数据类型 新名称
// 该结构体的类型为 struct OrderEntry, 该结构体的别名为 order
typedef struct OrderEntry
{
int order_no;
int total;
float price;
} order;
struct Date
{
int day;
int month;
int year;
};
// 5. 嵌套结构体定义
struct Person
{
char name[50];
struct Date birthday;
};
int main(int argc, const char *argv[])
{
printf("--------students---------\n");
struct Student stu1;
stu1.no = 1;
stu1.name = "steve";
stu1.sex = 'M';
stu1.score = 100;
printf("no = %d, name = %s, sex = %c, score = %.2f\n", stu1.no, stu1.name, stu1.sex, stu1.score);
printf("--------teachers---------\n");
t1.name = "bob";
t1.no = 1001;
t1.salary = 10000;
t2.name = "lisi";
t2.no = 1002;
t2.salary = 20005;
printf("no = %d, name = %s, salary = %.2f\n", t1.no, t1.name, t1.salary);
printf("no = %d, name = %s, salary = %.2f\n", t2.no, t2.name, t2.salary);
printf("--------cars---------\n");
car1.plate_no = "晋A69888";
car1.brand = "BMW";
car1.price = 598700;
car2.plate_no = "京A88888";
car2.brand = "Mercedes-Benz";
car2.price = 1500000;
printf("plate_no = %s, brand = %s, price = %.2f\n", car1.plate_no, car1.brand, car1.price);
printf("plate_no = %s, brand = %s, price = %.2f\n", car2.plate_no, car2.brand, car2.price);
printf("--------orders---------\n");
// order 是 struct OrderEntry 的别名
order ord1;
ord1.order_no = 9001;
ord1.total = 100;
ord1.price = 900000;
printf("order_no = %d, total = %d, price = %.2f\n", ord1.order_no, ord1.total, ord1.price);
printf("--------people---------\n");
struct Person p1;
strcpy(p1.name, "张三");
p1.birthday.year = 2005;
p1.birthday.month = 9;
p1.birthday.day = 20;
printf("name = %s, birthday = %4d-%02d-%2d\n", p1.name, p1.birthday.year, p1.birthday.month, p1.birthday.day);
return 0;
}
标签:stu1,语言,no,price,使用,struct,printf,结构,name
From: https://www.cnblogs.com/zxhoo/p/17600106.html