自定义的可用的数据类型

结构体 struct

struct student{
   
	int num;
	int scores;
}stu1,stu2,stu3;

student 结构体标签

num,scores 结构体中变量的定义

stu1,stu2,stu3 结构变量

定义在结构的末尾,最后一个分号之前可以指定一个或多个结构变量。

此外:

struct{
   		//无结构体标签 
	int a1;
	int b1;
}s1;

struct node1{
   
	int a2;
	int b2;
};//无声明变量
typedef struct node{
   
	int a3;
	int b3;
    struct node1 abb;
    struct node *next;
}s2,*sw;
//现在可以用s2作为类型声明新的结构体变量

主函数


int main(){
   
    struct node1 m;
	m.a2;

    // 访问结构成员 :
    // 为了访问结构的成员,我们使用成员访问运算符(.)
    sw qew;
    qew->abb.a2;//结构体指针的成员变量访问符
    s2 q;
	q.abb.a2;

    struct node qwe;
    qwe.a3;

    struct student stu5;
	stu5.num;
	
	return 0;
} 

例如:

struct Books
{
   
   char  title[50];
   char  author[50];
   char  subject[100];
   int   book_id;
} book = {
   "C 语言", "RUNOOB", "编程语言", 123456};
 
int main()
{
   
    printf("title : %s\nauthor: %s\nsubject: %s\nbook_id: %d\n", book.title, book.author, book.subject, book.book_id);
}

例题:

建立一个学生结构体数组,有三个学生元素。

结构体里有四个成员:学号,姓名,出生年月日(也是结构体变量),成绩。

编程实现这三个学生所有信息的输入,输出,并求出成绩的平均值输出。


struct birth{
   
	int year;
	int month;
	int day;
};
struct stu{
   
	int numb;
	char name[10];
	struct birth a;
	int score;
}student[5];

int main(){
   
	double sum=0;
	for(int i=0;i<3;i++){
   
		scanf("%d%s%d%d%d%d",&student[i].numb,student[i].name,&student[i].a.year,&student[i].a.month,&student[i].a.day,&student[i].score);
	}
	for(int i=0;i<3;i++){
   
		printf("%d %s %d %d %d %d\n",student[i].numb,student[i].name,student[i].a.year,student[i].a.month,student[i].a.day,student[i].score);
		sum+=student[i].score;
	}
	printf("成绩的平均值为:%.2lf",sum/3);
}

input:

1 zhang 1900 1 1 90
2 wang 1901 1 1 90
3 gao 1920 1 1 90

output:

1 zhang 1900 1 1 90
2 wang 1901 1 1 90
3 gao 1920 1 1 90
成绩的平均值为:90.00

结构体指针

指向结构体的指针

struct stu *pstu;

例如:

struct stu{
   
    int num;
    char *name;
    char sex;
    float score;
}boy1 = {
   006,"zhangzhang",'1',69.6};

int main() {
   

    struct stu *pstu;
    pstu = &boy1;

    printf("%d,%s\n", boy1.num, boy1.name);

    printf("%d,%s\n", (*pstu).num, (*pstu).name);

    printf("%d,%s\n", pstu->num, pstu->name);

}