结构体名字定义
#include <stdio.h>
struct Student //结构体名称一般大写
{
int id;
char* name;//指针常量(回顾)
int age;
float score;
};
//匿名结构体
typedef struct Student //结构体名称一般大写
{
int id;
char* name;//指针常量(回顾)
int age;
float score;
} stu1, stu 2;//变量
typedef struct Sdudent A;//typedef +结构体名称(一定是struct+..)+新名称
int main(){
A stu;//定义变量:结构体名称+变量=struct Student(int同等地位) stu;
Student stu1;
return 0;
}
结构体嵌套
#include <stdio.h>
typedef struct Student //结构体名称一般大写
{
int id;
char* name;//指针常量(回顾)
int age;
float score;
Birthday birthday;
} Student;
typedef struct Birthday {
int year;
int month;
int day;
}Birthday;
定义变量
第一种 正常在main函数里定义
#include <stdio.h>
typedef struct Student //结构体名称一般大写
{
int id;
char* name;//指针常量(回顾)
int age;
float score;
} Student;
int main(){
Student stu1;
return 0;
}
第二种 在结构体末尾留名
#include <stdio.h>
typedef struct Student //结构体名称一般大写
{
int id;
char* name;//指针常量(回顾)
int age;
float score;
} Student ,stu3;
变量赋值
#include <stdio.h>
typedef struct Student //结构体名称一般大写
{
int id;
char* name;//指针常量(回顾)
int age;
float score;
Birthday birthday;
} Student;
typedef struct Birthday {
int year;
int month;
int day;
}Birthday;
int main(){
Student stu1 = { 1001,"tom",27,98,{2004,8,11} };//直接大括号包起来
return 0;
}
访问结构体成员
方法一 只有一个对象,直接暴力打印
#include <stdio.h>
typedef struct Student
{
int id;
char* name;
int age;
float score;
Birthday birthday;
} Student;
typedef struct Birthday {
int year;
int month;
int day;
}Birthday;
int main(){
Student stu1 = { 1001,"tom",27,98,{2004,8,11} };
printf("%d \t %d \t %d \t",stu1.birthday.day, stu1.birthday.month,stu1.birthday.year);//用.一级一级推
return 0;
}
方法二 推荐制作打印函数,一劳永逸
2.1 传变量
#include <stdio.h>
void printfStudentInfo(Student stu)//Student 就是相当于int 牢记!
{
printf("%d \t %d \t %d \t", stu.birthday.day, stu.birthday.month, stu.birthday.year);
}
typedef struct Student
{
int id;
char* name;
int age;
float score;
Birthday birthday;
} Student;
typedef struct Birthday {
int year;
int month;
int day;
}Birthday;
int main() {
Student stu1 = { 1001,"tom",27,98,{2004,8,11} };
printfStudentInfo(stu1);
return 0;
}
2.2传指针 (见指针部分)
(类型)
结构体指针
#include <stdio.h>
void printfStudentInfo(Student *p)//传进来的是指针
{
printf("%d \t %d \t %d \t", p->birthday.day, p->birthday.month, p->birthday.year);//记忆方法 :指针->指,同等地位的仍用"."
}
typedef struct Student
{
int id;
char* name;
int age;
float score;
Birthday birthday;
} Student;
typedef struct Birthday {
int year;
int month;
int day;
}Birthday;
int main() {
Student stu1 = { 1001,"tom",27,98,{2004,8,11} };
Student* pstu = &stu1;//定义指针
printfStudentInfo(stu1);
return 0;
}
ps:传指针的记忆:
sizeof 的使用:
printf("%d",sizeof(int));
printf("%d", sizeof(Birthday));//再次强调Birthday 的地位等同于int,再没有简化声明之前=struct Birthday