什么是结构体
自定义的数据类型
结构体的声明定义
//1.先声明再定义
struct point{int x;int y;
};struct point p1,p2;//2.声明的同时定义
struct point{int x;int y;
}p1,p2;
typedef定义别名
关键字typedef用于为系统固有的或者程序员自定义的数据类型定义一个别名。数据类型的别名通常使用大写字母。
typedef int INTEGER;
这样就为int
定义了一个新的名字INTEGER
,in
t与INTEGER
是一个意思,是完全等价的。
所以,我们当然也可以使用typedef
来为结构体定义一个别名,让我们使用更加方便。
typedef struct student{char name[20]; long long id; int age; float score;
}STU;//声明结构体的同时起一个别名,STUDENT就相当于struct student
结构体内部变量的访问
访问格式:`结构体变量名`+`.`+`数据变量名`
#include <stdio.h>struct student{char name[20];//姓名int age;//年龄char gender;//性别long long id;//学号
};//先声明
typedef struct student STUDENT;//再起别名int main(){STUDENT st1;//初始化st1.age = 18;printf("%d",st1.age);//赋值初始化STUDENT stu= {"李华",18,'w',202231061201};return 0;
}
使用
结构体指针
#include <stdio.h>struct student{char name[20]; long long id; int age; char gender;
};
typedef struct student STUDENT;int main(){STUDENT *st1;//定义一个STUDENT类型的指针STUDENT stu;//定义一个STUDNET结构体st1 = &stu;//将是st1指针指向stust1->id = 202231061201;//注意用的是->scanf("%s",st1->name);scanf("%d",&st1->age);st1->gender = 'w';printf("%s%d岁了\n",st1->name,st1->age);printf("%s%d岁了",(*st1).name,(*st1).age);//st1指针解引用之后就与普通结构体变量一样用.return 0;
}
结构体数组
#include <stdio.h>struct student{char name[20];//姓名int age;//年龄char gender;//性别long long id;//学号
};
typedef struct student STUDENT;int main(){STUDENT stu[3] = {{"李华",18,'w',202231061201},{"小红",19,'m',202231061202},{"小明",20,'w',202231061203}};return 0;
}