#include<stdio.h>
//把没有命名的结构体称为亚元结构
struct Student//Student为结构体名称
{
char s_name[20];
int age;
}s1; //s1在这里是变量
struct Student s2; //s2与s1等价,结构体变量
typedef struct Student stud; //stud是类型,等价于在定义结构体时在其前直接加typedef-->typedef struct Student
//typedef把一切合法的变量定义变为类型声明,
typedef struct Student *pstd;//类型
int main()
{
struct Student x;
stud y;//x和y的定义等价
pstd p;//p是struct student*类型的
p = &x;//OK
//结构体数组
stud ar[]={"hello1",23,"hello2",22,"hello3",18};
int n=sizeof(ar)/sizeof(ar[0]);//n=3
//结构体输出方式
p = ar;//数组名称代表数组首元素地址
for(int i=0;i<n;i++)
{
printf("name:%s\tage:%d\n",ar[i].s_name,ar[i].age);
printf("name:%s\tage:%d\n",(p+i)->s_name,(p+i)->age);
//或者p[i].s_name,(*(p+i)).s_name;
}
}
#include<stdio.h>
//结构体大小
/*
由于存储变量地址对齐的问题,计算结构体大小的3条规则:
①结构体变量的首地址,必须是结构体变量中的“最大基本数据类型成员所占字节数”的整数倍。
②结构体变量中的每个成员相对于结构体首地址的偏移量,都是该成员基本数据类型所占字节数的整数倍。
③结构体变量的总大小为结构体变量中“最大基本数据类型成员所占字节数”的整数倍。
*/
//对齐:cpu读取内存时是以2,4,8的倍数的字节块来读写内存的。
//#pragma pack(n)可以改变默认对齐数,n取值是1,2,4,8,16
//限制比n小的字节数,不限制大的。
struct node1
{
char cha;
int ia;
char chb;
};
struct node2
{
char cha;
char chb;
int ia;
};
struct node3
{
char cha;
int ia;
short sa;
};
#pragma pack(1)//限制比n
struct node4
{
char cha;
int ia;
short sa;
};//字节数变为7
#pragma pack //结束
int main()
{
struct node1 s1={'a','b',12};
struct node1 s2={'a',12,'b'};
printf("s1 size:%d\tstruct node1 size:%d\n",sizeof(s1),sizeof(struct node1));
printf("s2 size:%d\tstruct node2 size:%d\n",sizeof(s2),sizeof(struct node2));
printf("struct node3 size:%d\n",sizeof(struct node3));
printf("struct node4 size:%d\n",sizeof(struct node4));
return 0;
}