一、结构体和数组的区别:
数组:只能由多个相同类型的数据构成;
结构体:可以由多个不同类型的数据构成;
二、结构体定义的三种形式:
int main() { //结构体定义的3种形式 //1. 定义结构体的时候声明变量 struct Person { // 里面的三个变量可以成为结构体的成员或者属性 doubleweight; char*name; intage; } stu,stu1; // 可以定义多个结构体变量,注意stu前面要有空格,后面有分号 //2.单纯的只定义结构体 struct Student { intno; };// 注意此处的分号不可忘掉 struct Students; //3.没有结构体名称,直接定义变量 struct { intage; } p;
三、 结构体初始化
(1)初始化形式
1>定义变量的时候初始化
struct Personpp = {10.2, "rose", 45};
printf("%d,%p",pp, &pp);
printf("年龄:%d, 姓名:%s,体重:%f\n", pp.age, pp.name,pp.weight);
2>先定义后赋值,结构体中给变量赋值用的是“.”
stu.age = 10;
stu.name ="jack";
stu.weight =50;
printf("%p,%d", &stu, stu);
printf("年龄:%d, 姓名:%s,体重:%f\n", stu.age, stu.name,stu.weight);
//3>
struct Student s1 = {10,"jack", 40.0};
struct Student s2 = {11,"rose", 45.0};
//s2所有成员的值都对应的赋值给s1
s1 = s2;
(2)初始化常见错误
struct Students2;
s2 = {14,"zhs", 20.0};
//类似的错误初始化:
int a[3];
a[3] = {1, 2,3};
四、结构体内存分析
void test1() { struct Student { intage; //4个字节 chara; //1个字节 doubleweight; //8个字节 char*name; //4个字节 }; struct Studentstu; int s =sizeof(stu); printf("%d",s); }
(1)补齐算法:
1>
2>struct Student { int age; //4 char a; //1 double weight; //8 } //sizeof(stu)的结果:16
struct Student { int age; //4 double weight; //8 char a; //1 } //sizeof(stu)的结果:24
3>
struct Student { int age; //4 char a; //1 int height;//4 } //sizeof(stu)的结果:12
(2)结构体内存细节
1>定义结构体类型的时候(并不会分配存数空间)
2>定义结构体变量的时候(才是真正分配存储空间)
五、结构体数组
#include <stdio.h> struct Date { intyear; intmonth; intday; }; struct Person { intage; char*name; structDate birthday; /*注意结构体的嵌套定义中 structPerson s;这种写法是错误的,自己不能嵌套自己 */ }; void test(struct Person); void test2(struct Person *); int main() { inti; structPerson p[3] = { {12, "jack", {2002, 1, 3}}, {13, "rose",{2003, 2, 3}}, {14, "Mike", {2003, 2, 4}}}; /*错误写法 structPerson p[3]; p[3]= { {12, "jack", {2002, 1, 3}}, {13, "rose", {2003, 2, 3}},{14, "Mike", {2003, 2, 4}}}; */ //指向结构体的指针的定义 structPerson *pp = p; /* 指针取值:pp->age ==p.age (*pp).age == p.age 变量取值:p.age */ for(i= 0; i<3; i++) { printf("%d, %s, %d-%d-%d\n",p[i].age, p[i].name, p[i].birthday.year, p[i].birthday.month,p[i].birthday.day); } for(i= 0; i<3; i++) { printf("%d, %s, %d-%d-%d\n", (pp+i)->age,(pp+i)->name, (*(pp+i)).birthday.year, (*(pp+i)).birthday.month,p[i].birthday.day); } test(p[0]); test2(&p[1]); return 0; } /*结构体与数组 */ void test(struct Person s) { structDate d = {2011,2,1}; s.age= 20; s.name= "rose"; s.birthday= d; printf("%d,%s, %d-%d-%d\n", s.age, s.name, s.birthday.year, s.birthday.month,s.birthday.day); } void test2(struct Person *p) { structDate d = {2011,2,1}; p->age= 21; p->name= "point"; p->birthday= d; printf("%d,%s, %d-%d-%d\n", p->age, p->name, p->birthday.year,p->birthday.month, p->birthday.day); }
六、结构体注意:
1>结构体类型不可重复定义
struct Student { int age; }; struct Student { char *name; }
2>结构体可以嵌套定义,但是自己不能嵌套自己
struct Student { int age; struct Student s; }; //这样写是不正确的
3>结构体初始化时不可以先定义后整体赋值
struct Student s2; s2 = {14, "zhs", 20.0};
4>定义结构体类型的时候内存没有分配存储空间,当定义结构体变量的时候才分配;
5>取结构体中的变量的值得时候应用“.”符号,如果是指针应用“->”符号;
6>注意结构体的补齐算法.