结构体 共同体 枚举
来源:百度文库 编辑:神马文学网 时间:2024/04/29 02:03:01
结构体
1、一般形式
Siruct<结构体名>
{<成员列表>};
2、变量说明
(1)先定义结构体类型,再说明结构体变量
一般形式为:
Struct 结构体名 变量名列表;
例:
/*定义结构体类型*/
struct student
{
long num;
char name[20];
char sex;
float score;
}
/*说明结构体变量*/
struct student student1,student2;
(2)在定义结构体的同时定义结构体变量
一般形式为:
struct 结构体名
{
成员表列;
} 变量表列;
例:
struct student
{
long num;
char name[20];
char sex;
float score;
}student1,student2;
(3)利用无名结构体说明结构体变量
一般形式为:
struct
{
成员表列;
}变量名表列;
struct
{long num;
char name;
char sex;
float score;
}student1,student2;
(4)利用重命名类型(typedef)说明结构体
一般形式为:
typedef 已定义的类型标识符 新标识符;
作用:利用新标识符代替原来已定义的类型标识符
例:
typedef int integer;
typedef float real;
分别用 integer和real代替系统中已存在的int和float类型,就可以用他们说明新的变量。
例:
integer a,b;
real c,d;
下面用typedef说明结构体
先定义新类型名:
Typedef struct
{
Long num;
Char name[20];
Char sex;
Float score;
}stud;
说明新的结构体变量:
STUD STUDENT1,STUDENT2;
注意点:
Typedef 不是创建新类型而只是为标识符取一个别名。
结构体的引用和初始化
引用结构体的常用方式是利用“.”(成员分量)运算符,一般形式为:
<结构体变量名>.<成员名>
例:
student1.num=2003001;
Strcpy(studet1.name,“Liping”)/*不能用student1.name=“Liping“;* /
Student1.sex=‘M’;
Student1.score=91.5;
第一种初始化:
struct student
{
long num;
char name[20];
char sex;
float score;
};
struct student student1={2003001,“Liping”,‘M’,91.35};
第二种初始化:
struct student
{
long num;
char name[20];
char sex;
float score;
} student1={2003001,“Liping”,‘M’,91.35};
第三种初始化:
struct student
{
long num;
char name[20];
char sex;
float score;
} student1={2003001,“Liping”,‘M’,91.35};
第四种初始化:
struct student
{
long num;
char name[20];
char sex;
float score;
}STUD;
STUD student1={2003001,“Liping”,‘M’,91.35};
结构体数组
P.178
结构体与函数
一般形式:
<结构体类型名><函数名>(<形式参数表>)
{
函数体
}
结构体指针
指向结构体变量的指针的一般形式:
<结构体类型名> *<指针变量名>;
注意:
1、成员运算符(.)的优先级比(*)的优先级高
2、使用“-”和“>”的复合形式“->”作为指向结构体成员的运算符.
例:p->num代替(*p).num
P_>name代替(*p).name
链表:
1、分配内存空间函数malloc
函数原形: void*malloc (unsigned int size);
调用形式:(<类型说明符>*)malloc (size)
2、释放内存空间的函数free
函数原形:void free(void *block);
调用形式:free(p);
注意:
使用这两个函数时要引用两个头文件“stdio.h”和“alloc.h”