结构体
结构体为一种开发者自己设计的数据类型
struct Studnt
{
char s_id[10];
char s_name[10];
char s_sex[6];
int s_age;
}; //";"必不可少
struct Student
{
char s_id[10];
char s_name[10];
char s_sex[8];
int s_age;
};
//void Print_Student(struct Student stud[], int n)
void Print_Student(struct Student *stud, int n) //sizeof(stud) //4字节
{
assert(stud != nullptr);
printf("%-10s %-10s %-8s %-5d\n", "id", "name", "sex", "age");
for (int i = 0;i < n;++i)
{
//printf("%-10s %-10s %-8s %-5d\n", stud[i].s_id, stud[i].s_name, stud[i].s_sex, stud[i].s_age); // (写法一)
//printf("%-10s %-10s %-8s %-5d\n", (*(stud + i)).s_id, (*(stud+i)).s_name, (*(stud + i)).s_sex, (*(stud + i)).s_age); // (写法二)
printf("%-10s %-10s %-8s %-5d\n", stud->s_id, stud->s_name, stud->s_sex, stud->s_age);
stud++;//(写法三)
}
printf("\n");
}
int main()
{
struct Student studx[10] = {
{"0901","yhping","man",23},
{"0901","chang","man",33},
{"0901","hexing","woman",13},
{"0901","lejian","man",24},
{"0901","liuxiao","woman",45},
{"0901","zhang","man",15},
{"0901","zhaowu","woman",22},
};
Print_Student(studx,7);
return 0;
}
结构体大小
由于存储变量地址对齐的问题,计算结构体大小的3条规则:
1.结构体变量的首地址,必须是结构体变量中的“最大基本数据类型成员所占字节数”的整数倍。
2.结构体变量中的每个成员相对于结构体首地址的偏移量,都是该成员基本数据类型所占字节数的整数倍。
3.结构体变量的总大小,为结构体变量中“最大基本数据类型成员所占字节数"的整数倍。
struct Node
{
char cha;
char chb;
int ia;//共8字节
//char cha; int ia; char chb; //共12字节
};
int main()
{
struct Node x = {'a','b',0x12345678};
int size = sizeof(x);
printf("%d \n", size);
}
struct node // double
{
char cha;
double da;
char chb;
};
sizeof(struct node);/ /24
struct node//数组
{
char ch[3];
int ia;
};
sizeof(struct node);//8