struct Person{
char name[22];
bool sex;
int age;
double score;
};
typedef struct
{
char title[50];
char author[50];
char subject[100];
int book_id;
}Books;
void printPerson(struct Person person){
cout << "name = " << person.name << endl;
cout << "sex = " << person.sex << endl;
cout << "age = " << person.age << endl;
cout << "score = " << person.score << endl;
}
void printPerson2(struct Person *person){
cout << "name = " << person->name << endl;
cout << "sex = " << person->sex << endl;
cout << "age = " << person->age << endl;
cout << "score = " << person->score << endl;
}
int main() {
count = 5;
write_extern();
Person p1;
Person p2;
Books books;
strcpy(books.author,"jack");
strcpy(p1.name,"tom");
p1.sex = false;
p1.age = 11;
p1.score = 89.5;
strcpy(p2.name,"tom2");
p2.sex = true;
p2.age = 22;
p2.score = 77.5;
printPerson(p1);
printPerson2(&p2);
return 0;
}
注意:结构体占用内存大小,存在内存对齐问题。
在 结构体中定义各个数据类型的时候,应该按照占用内存从大到小排列。
例如
// #pragma pack(1) //强制1字节对齐,效率会受到影响
struct Student
{
//char * p; //4
//char arr[2];//2 8
//short d; //2 16
//int c; //4
//long g;//4
//double f;//8 24
//float h[2];//8 40
//上面这是一种不优的写法!!!!!!,需要占用40个字节
double f;//8
float h[2];//8
long g;//4
int c; //4
char * p; //4
short d; //2
char arr[2];//2 这种写法一共才占用32个字节
}stu,stu1,stu2;
tips: 结构体嵌套的情况下,以2个结构体中最大的数据类型占用内存为主。总之就是向最大占用内存的数据类型对齐,包含double 就以8字节对齐
关于#pragma pack(1) 的更多详细介绍,可以参照文章:https://blog.csdn.net/xiao156520/article/details/41178805