结构体
土豆 2023/7/19 c
# 结构声明
struct Product{
char cName[10]; // 产品名称
char cShape[20]; // 形状
char cColor[10]; // 颜色
char cFunc[20]; // 功能
int iPrice; // 价格
char cArea[20]; // 产地
};
# 结构体变量的定义
# 定义方式一
struct Product{
char cName[10]; // 产品名称
char cShape[20]; // 形状
char cColor[10]; // 颜色
char cFunc[20]; // 功能
int iPrice; // 价格
char cArea[20]; // 产地
};
// 定义结构体变量
struct Product product1;
struct Product product2;
# 定义方式二
struct Product{
char cName[10]; // 产品名称
char cShape[20]; // 形状
char cColor[10]; // 颜色
char cFunc[20]; // 功能
int iPrice; // 价格
char cArea[20]; // 产地
} product1,product2;
# 嵌套定义
#include <stdio.h>
// 日期结构体
struct date{
int year; // 年
int month; // 月
int day; // 日
};
struct student{
int num; // 学号
char name[30]; // 姓名
char sex; // 性别
struct date birthday; // 出生日期
} student1,student2;
# 结构体变量的引用
#include <stdio.h>
#include <string.h>
struct Teacher{
char name[64];
int age;
int seniority;
};
int main() {
struct Teacher teacher;
// 将姓名赋值给结构体变量
strcpy(teacher.name,"张三");
teacher.age = 35;
teacher.seniority = 10;
printf("姓名:%s\n",teacher.name);
printf("姓名:%d\n",teacher.age);
printf("年龄:%d\n",teacher.seniority);
return 0;
}
# 结构体类型的初始化
# 声明时初始化
#include <stdio.h>
// 声明时初始化
struct Teacher{
char name[64];
int age;
int seniority;
} teacher1 = {"lisi",35,20};
# 定义时初始化
#include <stdio.h>
struct Teacher{
char name[64];
int age;
int seniority;
};
int main() {
// 定义时初始化
struct Teacher teacher1 = {"lisi",35,20};
return 0;
}
# 结构体数组
#include <stdio.h>
struct Student{
char cName[64]; // 姓名
int iNumber; // 学号
char cSex; // 性别
int iGarde; // 年级
};
int main() {
struct Student student[5] = {
{"zhansan",1,'M',3},
{"lisi",2,'W',3},
{"wangwu",3,'W',3},
};
return 0;
}
# 结构体指针
# 读取方式一
#include <stdio.h>
struct People{
char cName[20]; // 姓名
int iNumber; // 职位号
char cS[20]; // 部门
};
int main() {
struct People people = {"张伟",14,"开发部"};
// 结构体指针
struct People *p;
p = &people;
printf("---- 信息如下 --- \n");
printf("姓名: %s\n",(*p).cName);
printf("职工号: %d\n",(*p).iNumber);
printf("部门: %s\n",(*p).cS);
return 0;
}
# 读取方式二
#include <stdio.h>
struct People{
char cName[20]; // 姓名
int iNumber; // 职位号
char cS[20]; // 部门
};
int main() {
struct People people = {"张伟",14,"开发部"};
// 结构体指针
struct People *p;
p = &people;
printf("---- 信息如下 --- \n");
printf("姓名: %s\n",p->cName);
printf("职工号: %d\n",p->iNumber);
printf("部门: %s\n",p->cS);
return 0;
}