下面举一个例子来说明怎样定义结构体变量。
struct string{char name[8];int age;char sex[2];char depart[20];float wage1, wage2, wage3, wage4, wage5;}person;
这个例子定义了一个结构名为string的结构体变量person。还可以省略变量名person,做如下定义:
struct string{char name[8];int age;char sex[2];char depart[20];float wage1, wage2, wage3, wage4, wage5;};struct string person; //定义结构名为string的结构体变量person
struct string Liming, Liuqi, ...; struct{char name[8];int age;char sex[2];char depart[20];float wage1, wage2, wage3, wage4, wage5;} Liming, Liuqi;
结构变量.成员名 int main(){struct{char *name; //姓名int age; //年龄char group; //所在小组} stu1;//给结构体成员赋值stu1.name = "Tom";stu1.age = 18;stu1.group = 'A';//读取结构体成员的值printf("%s的年龄是%d,在%c组\n", stu1.name, stu1.age, stu1.group);return 0;}
struct{char name[8];char sex[2];int age;char addr[40];}student[40];
结构数组元素.成员名 student[0].namestudent[30].age
struct string{char name[8];char sex[2];int age;char addr[40];}*student;
结构体指针名->结构体成员 strcpy(student->name, "acket"); //student->name就是(*student).namestudent->age=18;
student=(struct string*)malloc(size of (struct string));//size of (struct string)是自动求取string结构体的字节长度
struct 位结构名{数据类型 变量名: 整型常数;数据类型 变量名: 整型常数;}位结构变量;
struct{unsigned incon: 8; /*incon占用低字节 的0~7共8位*/unsigned txcolor: 4;/*txcolor占用高字节的0~3位共4位*/unsigned bgcolor: 3;/*bgcolor占用高字节的4~6位共3位*/unsigned blink: 1; /*blink占用高字节的第7位*/}ch;
ch.bgcolor struct info{char name[8];int age;struct address addr;unsigned char state:1;unsigned char payyyy:1;}people;
typedef struct person{int age ;char *name;char *sex;}student;student stu1; //此处可以用student来定义一个结构体变量