结构体自引用
struct node
{
int data;
struct node* next;
};
结构体重定义
typedef struct node
{
int data;
struct node* next;
}node;//重定义结构体名为node
int main()
{
node n = { 0 };
return 0;
}
结构体变量创建
struct stu
{
char name[20];
int age;
}s1,s2;//顺着结构体变量创建
int main()
{
struct stu s3,s4;
return 0;
}
结构体内存对齐
struct s1
{
int a;//占四个字节(0-3)
char b;//占一个字节(4)
char c;//占一个字节(5)
};//因为结构体总字节是最大对齐数(4)的整数倍,所以浪费两个字节(6-7),共占八个字节(0-7)
struct s2
{
char a;//占一个字节(0),但由于下一个参数是int型,必须从自己对齐数(即自身大小4)整数倍开始,所以要浪费三字节(1-3)
int b;//占四个字节(4-7)
char c;//占一个字节(8)
};//因为结构体总字节是最大对齐数(4)的整数倍,所以浪费三个字节(9-11),共占十二个字节(0-11)
结构体嵌套内存对齐
struct s3
{
double a;//占八个字节(0-7)
char b;//占1个字节(8),但由于下一个参数是int型,必须从自己对齐数(即自身大小4)整数倍开始,所以要浪费三字节(9-11)
int c;//占四个字节(12-15)
};//因为结构体总字节是最大对齐数(8)的整数倍,正好占十六个字节(0-15)
struct s4
{
char d;//占一个字节(0),但由于下一个参数是嵌套的结构体,必须从该结构体自己最大对齐数(即double类型的8)整数倍开始,所以要浪费七字节(1-7)
struct s3;//占十六个字节(8-23)
double e;//占八个字节(24-31)
};//因为结构体总字节是最大对齐数(8)的整数倍,正好占三十二个字节(0-31)
枚举
enum color
{
red,
blue,
green
};
int main()
{
printf("%d\n", red);//0
printf("%d\n", blue);//1
printf("%d\n", green);//2
}
enum color
{
red=4,
blue,
green
};
int main()
{
printf("%d\n", red);//4
printf("%d\n", blue);//5
printf("%d\n", green);//6
}
enum color
{
red,
blue=8,
green
};
int main()
{
printf("%d\n", red);//0
printf("%d\n", blue);//8
printf("%d\n", green);//9
}
enum color
{
red=4,
blue=7,
green=1
};
int main()
{
printf("%d\n", red);//4
printf("%d\n", blue);//7
printf("%d\n", green);//1
}
联合体
union un
{
char c;
int a;
};
int main()
{
printf("%d\n", sizeof(union un));//4
union un u1;
printf("%p\n", &u1);
printf("%p\n", &(u1.a));
printf("%p\n", &(u1.c));
}//联合体的大小最小为最大成员大小,其成员共用一个地址
union un
{
char c[5];//对齐数为1
int a;//对齐数为4
};
int main()
{
printf("%d\n", sizeof(union un));//8
}//联合体的大小最小为最大成员大小且是成员最大对齐数的最小整数倍
联合体判断大端小端
union un
{
char c;
int a;
};
int main()
{
union un u1 = { 0 };
u1.a = 1;
if (u1.c == 1)
printf("小端");
else
printf("大端");
return 0;
}