typedef是类型定义的意思。typedef struct 是为了使用这个结构体方便。
1、结构体
1)、结构体变量的定义可以放在结构体的声明之后:
struct Student{ //声明结构体 char name[20]; //姓名 int num; //学号 float score; //成绩 }; struct Student stu1; //定义结构体变量
2)、结构体变量的定义也可以与结构体的声明同时,这样就简化了代码:
struct Student{ char name[20]; int num; float score; }stu1; //在定义之后跟变量名
3)、还可以使用匿名结构体来定义结构体变量:
struct { //没有结构名 char name[20]; int num; float score; }stu1;
但要注意的是这样的方式虽然简单,但不能再次定义新的结构体变量了。
访问结构成员
但如果结构体中的成员又是一个结构体,如:
struct Birthday{ //声明结构体 Birthday int year; int month; int day; }; struct Student{ //声明结构体 Student char name[20]; int num; float score; struct Birthday birthday; //生日 }stu1;
#include
//定义结构体并声明变量 struct people { int age; int id; }a; int main() { a.age = 20; printf("%d\n", a.age); }
2、typedef修饰的结构体
#include
struct people { int age; int id; }a;//a代表什么? typedef struct cat { int age; int id; }b; int main() { a.age = 20; printf("%d\n", a.age); //cat结构体被typedef修饰,表示已经把cat结构体定义为一种类型,这样就可以这样定义一个cat类型的变量b b1,b tom,b robin b tom; tom.age=100; printf("%d\n", tom.age); return 0; }
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/202528.html原文链接:https://javaforall.net
