内存对齐的三大原则:
1>如果结构体里面的成员变量都是基本数据类型(int,char,float,double,指针),第一个成员变量从内存偏移量为0开始分配;后面的成员变量从内存偏移量是它本身的字节数的倍数开始分配;
2>如果成员变量中含有结构体成员变量或者数组,比如说struct Student{ char sex;int age;};从内存偏移量为成员变量字节数最大的字节数(int)的倍数开始分配
3>最后收尾的时候,所有的字节数要是最大字节数成员变量的倍数
*/
void test1()
{
//struct Student是我们自己定义的一个新的数据类型
struct Student
{
char name[20];
int age;
float score;
};
//数据类型+变量名;
struct Student stu1={"sq",10,100.0};
struct Student stu2;
// . 语法:相当于‘的’
stu2.age=10;
stu2.score=99.0;
strcpy(stu2.name, "rose");
printf("name=%s\nage=%d\nscore=%f\n",stu1.name,stu1.age,stu1.score);
/*
数组是一个集合类:相同类型的变量
结构体也是一个集合类:可以相同,可以不同类型的变量
*/
}
void test2()
{
struct Student
{
char sex;//0
float score;//4--7
double kill;//8---15
long age;//16--19
};
long size=sizeof(struct Student);
printf("size=%ld\n",size);
}
void test3()
{
struct Birthday
{
int year;//0---3
int month;//4---7
int day;//8---11
};
struct Student
{ int age;//0---3
char name[20];//4----23
struct Birthday birth;//24----35
};
//1.
struct Student stu={10,"sq",{1990,1,1}};
//2.
struct Student stu2;
stu2.age=20;
strcpy(stu2.name,"rose");
stu2.birth.year=2000;
stu2.birth.month=1;
stu2.birth.day=1;
printf("%ld\n",sizeof(struct Student));
}
void test4()
{
//1.
struct Student {
char sex;
int age;
}stu2[3]={{'x',10},{'s',10},{'c',10}};
//2.无名结构体
struct
{
int age;
char name[20];
}stu;
struct
{
int age;
char name[20];
}stu1;
}
void test5()
{
//是将现有的数据类型重命名成你想要的数据类型
typedef int size;
struct Student
{
char sex;
int age;
};
typedef struct Student Student;
typedef struct Person
{
char sex;
int age;
}Person;
struct Person p={'x',10};
Person p1={'m',20};
}
void test6()
{
typedef struct Student
{
char sex;
int age;
}Student;
Student stu={'x',10};
Student *p=&stu;
(*p).sex='m';
(*p).age=20; printf("sex=%c\nage=%d\n",stu.sex,stu.age);
p->sex='n';
p->age=30;
printf("sex=%c\nage=%d\n",stu.sex,stu.age);
}
/* 将stu[4]={{'x',30},{'x',11},{'x',40},{'x',13}};写一个函数实现年龄从小到大排序,排序完写一个函数打印信息
*/
typedef struct Student
{
char sex;
int age;
}Student,* pStudent;
/*
typedef struct Student Student;
typedef struct Student * pStudent;
*/
void printInfo(Student stu[],int size)
{
int i=0;
for (; istu[j].age)
{
Student temp=stu[i];
stu[i]=stu[j];
stu[j]=temp;
}
}
}
}int main()
{
Student stu[4]={{'v',40},{'x',11},{'f',50},{'m',13}};
// int arr[10]={12,3};
// int size1=sizeof(arr)/sizeof(int);
int size=sizeof(stu)/sizeof(Student);
printf("排序之前:\n");
printInfo(stu,4);
blueSort(stu,4);
`printf("排序之后:\n"); printInfo(stu,4);
return 0;
}