结构体与结构体指针数组
2021-03-11 本文已影响0人
Dalvik_
1.结构体定义与使用。
// 结构体的定义
struct Student {
char *name;
int age;
};
//结构体定义对象别名
struct Student1 {
char *name;
int age;
} student1;
int main() {
//结构体赋值使用
// struct Student student = {"老五", 20};
struct Student student;
student.name = "钻石王老五";
student.age = 12;
printf("Student的name:%s, age:%d\n", student.name, student.age);
//结构体别名
student1.name = "黑豹老六";
student1.age = 88;
printf("student1的name:%s, age:%d\n", student1.name, student1.age);
return 0;
}
2.结构体指针 与 动态内存开辟。
// 结构体的定义
struct Student {
char *name;
int age;
};
int main() {
//定义结构体指针 动态开辟内存
struct Student *structStudent = malloc(sizeof(struct Student));
structStudent->name = "大刀豆子";
structStudent->age = 99;
printf("structStudent的name:%s, age:%d\n", structStudent->name, structStudent->age);
free(structStudent);
structStudent = NULL;
return 0;
}
3.结构体的数组。
// 结构体的定义
struct Student {
char *name;
int age;
};
//结构体数组
int main() {
//静态开辟
struct Student student[10];
student->name = "美男子";
student->age = 100;
(student + 1)->name = "花少女";
(student + 1)->age = 99;
// student[1].name = "花少女";
// student[1].age = 99;
printf("Student[0]的name:%s, age:%d\n", student->name, student->age);
printf("Student[1]的name:%s, age:%d\n", student[1].name, student[1].age);
//结构体数据动态开辟
struct Student *student2 = malloc(3 * sizeof(struct Student));
student2->name = "美男子";
student2->age = 100;
(student2 + 2)->name = "花少女";
(student2 + 2)->age = 99;
printf("Student2[0]的name:%s, age:%d\n", student2->name, student2->age);
printf("Student2[2]的name:%s, age:%d\n", (student2 + 2)->name, (student2 + 2)->age);
free(student2);
student2 = NULL;
return 0;
}
4.结构体与结构体指针 取别名。
// 结构体的定义
struct Student {
char *name;
int age;
};
//结构体别名
typedef struct Student _Student;
//结构体指针别名
typedef struct Student *__Student;
//定义结构体并同时取别名
typedef struct {
char *name;
int age;
} Stu;
int main() {
_Student student;
student.name = "张三";
student.age = 10;
printf("student的name:%s, age:%d\n", student.name, student.age);
__Student student2 = malloc(sizeof(__Student));
student2->name = "李四";
student2->age = 20;
printf("student2的name:%s, age:%d\n", student2->name, student2->age);
free(student2);
student2=NULL;
Stu *stu = malloc(sizeof(Stu));
stu->name = "王五";
stu->age = 12;
printf("stu的name:%s, age:%d\n", stu->name, stu->age);
free(stu);
stu = NULL;
return 0;
}
5.枚举。
//枚举定义
enum Type {
One, Two
};
//枚举的定义并取别名
typedef enum {
Three, Four
} Type1;
int main() {
enum Type type = Two;
Type1 type1 = Three;
printf("type的值:%d\n", type);
printf("type1的值:%d\n", type1);
return 0;
}