1 为什么要使用“结构”(结构体)
需要表示一些复杂信息时,使用单纯的数据类型很不方便。
比如:学生信息(学号,姓名,班级,电话,年龄)
2 什么是“结构”
结构,就是程序员自定义的一种“数据类型” 是使用多个基本数据类型、或者其他结构,组合而成的一种新的“数据类型”。
3 结构的定义
struct 结构名 {
成员类型 成员名;
成员类型 成员名;
};
示例:(表示学生信息(姓名,班级,电话,年龄))
struct student {
char name[16];
int age;
char tel[12];
};
特别注意:
1)要以 struct 开头
2)最后要使用分号
3)各成员之间用分号隔开
4 结构体的初始化
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//结构,就是程序员自定义的一种“数据类型”
struct student {
char name[16];
int age;
char tel[12];
};
//结构体包含结构体的情况
struct _class{
struct student evan;
struct student martin;
struct student zsf;
};
int main(void){
//结构体的初始化
//方式一 定义的时候初始化所有的属性
struct student rock = {"evan", 38, "******"};
printf("rock 的姓名: %s 年龄: %d 电话: %s\n", evan.name, evan.age, evan.tel);
//方式二 定义的时候我们可以指定初始化的属性(VS/VC 不支持,但 gcc 是 支持的)
struct student s1 ={.name="张三丰",.age = 100};
//方式三 单独初始化每一个属性
struct student s2;
strcpy(s2.name, "杨过");
s2.age = 40;
s2.tel[0]='\0';
printf("杨过的姓名: %s 年龄: %d 电话: %s\n", s2.name, s2.age, s2.tel);
//结构体中含有结构体
struct _class c1={{"evan", 38, "******"},{"Martin", 38, "18684518289"},{"张三丰",100,""}};
printf("c1 班 martin 同学的姓名: %s 年龄: %d 电话: %s\n", c1.martin.name, c1.martin.age, c1.martin.tel);
system("pause");
return 0; }
使用形式:
结构体变量.成员变量
中间用 . 分隔
5 结构体的使用
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student {
char name[16];
int age;
};
int main(void){
struct student s1;
struct student s2;
printf("请输入第一个学生的姓名:\n");
scanf_s("%s",s1.name, sizeof(s1.name));
printf("请输入第一个学生的年龄:\n");
scanf("%d", &s1.age);
printf("第一个学生的姓名: %s, 年龄: %d\n", s1.name, s1.age);
//结构体的小秘密,结构体变量之间可以直接赋值
s2 = s1;
memcpy(&s2, &s1, sizeof(struct student));
printf("第二个学生的姓名: %s, 年龄: %d\n", s2.name, s2.age);
system("pause");
return 0;
}
注意:数组不能直接赋值
char c1[16]={"martin"};
char c2[16];
c2 = c1; //错误,数组不能直接赋值