结构体

1.简单认识结构体

#include<stdio.h>

/*struct tag(member list)(varible list)*/

                     成员列表     变量列表

struct stu

{

char name[20];

int age;

char sex[5];

char tele[12];

char addr[30]; 

};

int main()

{

struct stu stu2;

struct stu arr[10];

return 0;

}

2.结构体的重命名

①.typedef struct stu stu;

/*将结构体struct stu改为stu,便于后面的书写*/

②.typadef stu* pstu;

/*重命名一个结构体指针*/

3.结构体成员的访问

访问结构体成员的时候要用到结构体操作符“.”和“->”。

①直接访问(".")

int main()

{

stu stu;

strcpy(stu.name,“bit”);

/*将字符串“bit”放到数组arr中去,不可用直接赋值的方式,因为stu.name为一个地址常量*/

stu.name=20;

printf(“name=%s\n”,stu.name);

printf("age=%d\n",stu.age);

return 0;

}

②间接访问(“->”)

int main()

{

stu stu;

stu pstu=&stu;

strcpy((*pstu),"bit");

(*pstu).age=20;

return 0;

}

4.需要注意的

①.结构体的自引用

例:#include<stdio.h>

struct A

{

char name[20];

int age;

struct A sa;

};

/*以上是一种错误的写法,不可直接对结构体进行自引用*/

改进方法:

#inlcude<stdio.h>

struct A

{

char name[20];

int age;

struct A* pa;

};

int main()

{

struct A  sa1;

struct A  sa2;

struct A  sa3;

sa1.pa=&sa2;

sa2.pa=&sa3;

sa3.pa=NULL;

return 0;

}

/*通过指针的解引用访问到结构体,从而进行自引用*/

②.对结构体进行重命名的时候最好不要使用匿名

struct A

{

char name[20];

int age;

struct A  *pa;

}a;

③.不完全声明

struct B;

struct A

{

struct B *b;

}

/*在进行结构体嵌套引用时,如果嵌套结构体未经过声明,则需要在前面不完全声明*/

5.结构体初始化

int main ()

{

struct stu stu={"bit",20."nv","xi'an"};

printf("%s\n".stu.name);

return 0;

}

6.结构体内存分配

①.默认的对齐数是8

②.linux默认的对齐数是4

③.结构体的总大小是成员最大类型所占字节的整数倍

④.当两个结构体嵌套时,结构体的大小,嵌套结构体对齐到自己最大对齐数的整数处

⑤.每个结构体成员所分配的大小(对齐数)取本身大小与默认大小的较小值

⑥.在设计结构体成员顺序时,遵循将所占字节小的变量集中在一起的原则,可以节省内存空间。

⑦.当结构体作为函数参数的时候,传址的方式优于传值的方式

例1:#include<stdio.h>

struct S

{

int a;  

char c;

double d;

};

struct  S2

{

int a;

double d;

char c;

struct S ss;

};

此时struct C的大小为40个字节

例2:struct  S

{

int a;//第一个成员变量放在0偏移处  4  8 取4

char  c;//1 8 取1

double d;//8 8 取8

};