一:定义结构体
struct student{
char name[21];
int age;
double weight;
char sex;
bool yanzhi;
};
1.结构体放main函数上面才能在整个程序中使用它。
2.结构体成员可以用C++的类(如string),但是不提倡。
string name=''钟佳铭''尽量写成char name[50]=''钟佳铭''
3.C++中,结构体成员可以有函数,但是不提倡。
二:创建结构体变量
初始化可以大括号里 放个0或者不放,但是一定要初始化。
student a = {0};
//或者
student a = {};
如果想给每个成员赋初始值,可以在值填在花括号里(对应着填)。
student a = {"钟佳铭",18,60.5,'Y',true};
C++ struct关键字可以不写。
也可以在定义结构体时候创建结构体变量。
struct student {
char name[21];
int age;
double weight;
char sex; // 假设用 'Y' 表示男性,'X' 表示女性
bool yanzhi;
}a = { "钟佳铭", 18, 60.5, 'Y', true };
三:结构体占内存情况
用sizeof运算符可以得到整个结构体占用内存的大小。
但是结构体占的内存不一定等于全部成员占用内存之和。
#include <iostream>
using namespace std;
struct student {
char name[21];
int age;
double weight;
char sex; // 假设用 'Y 表示男性,'X' 表示女性
bool yanzhi;
}a = { "钟佳铭", 18, 60.5, 'Y', true };
int main() {
// 输出结构体a所占用的字节数
cout << sizeof(a) << endl;
return 0;
}
貌似应该是21+4+8+1+1=35,实际上运行出48,这是由于内存对齐规则。
但是在C++中如下指令可以修改内存对齐规则。
#pragma pack(1)
#include <iostream>
using namespace std;
#pragma pack(1)
struct student {
char name[21];
int age;
double weight;
char sex; // 假设用 'Y 表示男性,'X' 表示女性
bool yanzhi;
}a = { "钟佳铭", 18, 60.5, 'Y', true };
int main() {
// 输出结构体a所占用的字节数
cout << sizeof(a) << endl;
return 0;
}
这样输出的就是35了。
四:清空结构体
memset() 和 bzero()都可以用来清空结构体。
memset(&a,0,sizeof(a));
//第一个参数结构体变量的地址,第二个参数填0,第三个参数填结构体的大小。
bzero(&a,sizeof(a));
//第一个参数结构体变量的地址,第二个参数填结构体的大小。
五:结构体的复制
1.用memcpy()
2.直接用等号。
#include <iostream>
#include <cstring> // 包含 memset 函数
using namespace std;
struct student {
char name[21];
int age;
double weight;
char sex; // 假设用 'Y' 表示男性,'X' 表示女性
bool yanzhi;
};
struct student a = { "钟佳铭", 18, 60.5, 'Y', true };
int main() {
struct student b;
memset(&b, 0, sizeof(b)); // 将结构体 b 的所有字节设置为 0
b = a; // 复制结构体 a到结构体b
// 打印结构体b的内容以验证复制是否成功
cout << "Name: " << b.name << endl;
cout << "Age: " << b.age << endl;
cout << "Weight: " << b.weight << endl;
cout << "Sex: " << (b.sex == 'Y' ? "Male" : "Female") << endl;
cout << "Yanzhi: " << (b.yanzhi ? "true" : "false") << endl;
return 0;
}