结构体与共用体
定义
//定义方法1
struct stu//取结构体名
{
int num;
char name[20];
char sex;
float score;
};//分号易遗忘
struct stu boy1,boy2;
//定义方法2
struct stu
{
int num;
char name[20];
char sex;
float score;
}boy1,boy2;
//定义方法3
struct
{
int num;
char name[20];
char sex;
float score;
}boy1,boy2;
struct stu *pstu;//结构指针
//访问结构体变量成员的方式
pstu->num;
(*pstu).num;//括号不能去,因为.的优先级高于*
动态内存分配
1.malloc
(类型说明符*)malloc(size);
功能:在动态存储区分配一块长度为“size”字节的连续区域,返回该区域的首地址。
2.calloc
(类型说明符*)calloc(n,size);
功能:在动态存储区分配n块长度为“size”字节的连续区域。
3.free
free(*ptr);
功能:释放ptr所指向的一块内存空间。
链表
//结构体定义
struct stu
{
int num;
int score;
struct stu *next;
};
建立
struct stu *head;
head = (struct stu*)malloc(sizeof(struct stu));//建立头指针,头指针没有数据
//插入第一个元素
struct stu *pf,*pb;//pb用来分配内存单元,pf用来指向链表最后一个元素
pb = (struct stu*)malloc(sizeof(struct stu));
pf=pb;
head->next=pf;
pf->next=NULL;
查找和输出
//查找所有num=x的元素,并输出分数
pb=head->next;
while(pb!=NULL){
if(pb->num==x){
printf("%d/n",pb->score);
}
else
pb=pb->next;
}
结点插入
//假如现在链表中已经有一个节点和头指针
//尾插法
pb=(struct stu*)malloc(sizeof(struct stu));
pf->next=pb;
pb->next=NULL;
pf=pb;//始终让pf指向最后一个节点
//头插法
pb=(struct stu*)malloc(sizeof(struct stu));
pf=head->next;//记住head本来的下一个节点,以防丢失
head->next=pb;
pb->next=pf;
结点删除
//删除num为x的节点
pb=head;
while(pb->next!=NULL){
if(pb->next->num==x){
struct stu *pt;
pt=pb->next;
pb->next=pt->next;
free(pt);//释放内存空间
}
else
pb=pb->next;
}
枚举类型
enum 枚举名{枚举值表};
enum weekday{Sun,Mon,Tue,Wed,Thu,Fri,Sat}a,b,c;
enum weekday x,y,z;
x=Sun;
值得注意的是,枚举值是常量,不能在赋值。枚举元素本身由系统定义了一个表示序号的数值,从0开始顺序定义。如代码中,Sun值为0,Mon值为1…
typedef
自己定义类型说明符
typedef int INTEGER;
INTEGER a,b;//INTEGER 就相当于int
typedef struct stu{
char name[20];
int age;
char sex;
}STU;
STU body1,body2;//STU 就相当于struct stu