结构体、用户自定义数据类型与共用体
结构体
结构体关键字:student
#include <stdio.h>
#include <string.h>
int main()
{
struct student{
int SID;
char name[20];
float math;
};
struct student st1={191011,"Wang Lin",92.0f};
struct student ast[10]={
{181021,"Zhang Kai",78.0f},
{181022,"Jin Shan",67.0f},
{181023,"Bai Neng",78.2f}
};
struct student *stp=ast;
struct student *stp1=&st1;
int i;
st1.SID=180912;
strcpy(st1.name,"Hong Kai"); //name 只是一个常量,不能赋值
st1.math=67.0f;
ast[3].SID=180914;
strcpy(ast[3].name,"Li XinXin");
ast[3].math=88.0f;
/* '.'号运算符
结构体 变量名.成员 ast[i].SID , (*stp).SID
'->‘号运算符
结构体 指针变量->成员 stp->SID (&ast[i])->SID
*/
printf("Student ID=%d,Name=%s,Score=%0.2f\n",st1.SID,st1.name,st1.math);
printf("\n");
for(i=0;i<4;i++)
printf("Student ID=%d,Name=%s,Score=%0.2f\n",
ast[i].SID,ast[i].name,ast[i].math);
printf("\n");
stp=ast;
for(i=0;i<4;i++,stp++)
printf("Student ID=%d,Name=%s,Score=%0.2f\n",
stp->SID,stp->name,stp->math);
}
用户自定义数据类型
用户自定义数据类型 关键字: typedef
typedef float FLT; 用户自定义一个单精度浮点类型(改名了)
typedef float *FP; 用户自定义一个FP浮点型指针类型
用户自定义数据类型最常见在结构体数据类型定义
#include <stdio.h>
typedef struct student
{
int SID;
char name[20];
FLT math;
struct student *next;
}STUDENT,*STP
int main()
{
STP Head; //结构体student类型指针 ==> struct student *head;
STUDENT *Current,*p; //结构体student类型指针 ==> struct student *Current,*p;
}
共用体
共用体 关键字:union
#include <stdio.h>
#include <string.h>
//建立一个用于学校职员的级别的共同体类型
union Level
{
char title[6]; //教师职称
int rank; //职员的级别
float admin; //行政级别
}
int main()
{
union Level a;
strcpy(a.title,"prof");
a.rank=4;
a.admin=1.5;
printf("Admin=%0.2f\n",a.admin);
}
结构体与共同体的异同点:
结构体和共同体都是由多个不同类型的数据组成:结构体同时保存所有成员的数据,共同体只保存最后赋值一个成员的数据;
结构体分别对各个成员赋值后,所有成员的值不会相互影响;但共同体则只能保存最后被赋值成员的数据;
结构体和共同体对成员引用方式-样:只能弓|用其中-一个成员的值;
结构体所占的存储空间为所有成员所需的空间之和;共同体则占最大成员的存储空间;
共同体内存空间为所有成员共享。