结构体
784字约3分钟
2025-05-28
结构体
结构体每次调用的的结果都可以不同
#include <stdio.h>
#include <string.h>
// He是结构体的标签,不可用做变量
struct He
{
char name[100];
int age;
double height;
};
void main()
{
struct He he;
strcpy(he.name, "hello");
he.age = 20;
he.height = 1.98;
printf("%s\n", he.name); // hello
printf("%d\n", he.age); // 20
printf("%.2lf\n", he.height); // 1.98
}
结构体简写(别名)
#include <stdio.h>
#include <string.h>
typedef struct
{
char name[100];
int age;
double height;
// H是结构体的别名,可以用作变量
} H;
void main()
{
H h;
strcpy(h.name, "hell");
h.age = 2;
h.height = 1.9;
printf("%s\n", h.name); // hell
printf("%d\n", h.age); // 2
printf("%.2lf\n", h.height); // 1.90
}
综合练习
#include <stdio.h>
#include <string.h>
typedef struct
{
char name[100];
int age;
} Stu;
// 细节:声明要写在结构体后面
void Xiu(Stu *p);
void main()
{
Stu s;
strcpy(s.name, "hi");
s.age = 0;
Xiu(&s);
// Xiu(s);
printf("初始化之后:%s,%d", s.name, s.age);
}
/*
细节:结构体中写了一个结构体变量,相当于定义了一个新变量
此时是把main函数中 s 的数据,传给新函数中的 st
void Xiu(Stu st)
在函数中修改st的值,不会影响s中的值
*/
// 如果要改变main函数中传入的值,则通过指针修改
void Xiu(Stu *p)
{
printf("初始化前:%s,%d\n", (*p).name, (*p).age);
printf("请输入姓名:");
scanf("%s", (*p).name);
printf("输入年龄:");
scanf("%d", &((*p).age));
printf("初始化之后:%s,%d\n", (*p).name, (*p).age);
}
嵌套结构体
#include <stdio.h>
#include <string.h>
typedef struct
{
char phone[15];
char email[15];
} Email;
typedef struct
{
char name[100];
char age;
Email e;
} Xin;
void main()
{
Xin x;
strcpy(x.name, "zhangsan");
x.age = 20;
strcpy(x.e.phone, "123456789");
strcpy(x.e.email, "123456@qq.com");
printf("姓名:%s\n", x.name);
printf("年龄:%d\n", x.age);
printf("电话:%s\n", x.e.phone);
printf("邮箱:%s\n\n", x.e.email);
// 一键赋值
// 如果结构体中又调用一个结构体
// 并且要给该结构体赋值,则需要使用一个大括号表示给该结构图赋值
Xin x1 = {"lisi", 18, {"1888888", "232443@qq.com"}};
printf("姓名:%s\n", x1.name);
printf("年龄:%d\n", x1.age);
printf("电话:%s\n", x1.e.phone);
printf("邮箱:%s\n", x1.e.email);
}
姓名:zhangsan
年龄:20
电话:123456789
邮箱:123456@qq.com
姓名:lisi
年龄:18
电话:1888888
邮箱:232443@qq.com
结构体的内存大小
#include <stdio.h>
/*
结构体的内存大小,是最大类型的整数倍(用来确定数据的补位情况)
对齐的时候会补充空白字节,但不会改变原来数据类型的字符大小
内存地址 % 占用地址 = 0
*/
struct Num
{
// char 占用一个字节,但是后面的1 2 3 % int的占用大小 不等于 0
// 所以char之后要补三个空字节
// 到 4 的时候可以被int的占用大小整除,所以 4 5 6 7表示的是int的类型
// 同理,8 可以被double占用大小整除,所以 8 9 10 11 12 13 14 15表示double类型
// 所以该及结构体的内存大小为 16
char a; // 0 1 2 3
int b; // 4 5 6 7
double c; // 8 9 10 11 12 13 14 15
// 小的数据类型写在最前面,大的数据类型写在最后面,这样节省内存
};
void main()
{
struct Num m;
printf("%d", sizeof(m)); // 16
}