C生万物 ● 大道至简 ● 鲍鱼科技
对应的视屏链接:C语言零基础入门_哔哩哔哩_bilibili
目录
目标
认识结构体类型
掌握结构体的基本定义和使用
一、结构体概述
结构体属于自定义类型,体现了程序由简单到复杂的变化过程。
C 数组允许定义可存储相同类型数据项的变量,结构是 C 编程中另一种用户自定义的数据类型,它允许存储不同类型的数据项。
二、结构体定义语法
struct tag_name
{
member-list
member-list
member-list
...
};
tag_name 是结构体类型名
member-list 是结构体成员列表,可以是任意合法类型。
例如:
struct Test
{
char a;
double b;
int c;
};
三、结构体定义的形式
1、标准形式
struct Test
{
char a;
double b;
int c;
};
2、定义类型的同时定义结构体变量
struct Test
{
char a;
double b;
int c;
}t1, t2[5], *pt;
3、省略结构体名
struct
{
char a;
double b;
int c;
}t1;
4、typedef类型定义
typedef struct
{
char a;
double b;
int c;
}Test;
四、定义结构体变量
#include<stdio.h>
struct Test
{
char a;
double b;
int c;
};
int main()
{
struct Test t;
return 0;
}
注:C语言使用结构体时,需要加struct关键字
五、结构体初始化
#include<stdio.h>
struct Test
{
char a;
double b;
int c;
};
int main()
{
struct Test t = {'A', 12.34, 100};
return 0;
}
六、结构体成员访问
#include<stdio.h>
struct Test
{
char a;
double b;
int c;
};
int main()
{
struct Test t = {'A', 12.34, 100};
printf("t.a = %c\n", t.a);
printf("t.b = %lf\n", t.b);
printf("t.c = %d\n", t.c);
return 0;
}
为了访问结构的成员,我们使用成员访问运算符(.)。成员访问运算符是结构变量名称和我们要访问的结构成员之间的一个点号。
七、结构体传参
1、传值操作
#include<stdio.h>
struct PersonInfo
{
char name[10];
int age;
char sex[3];
float height;
};
void PrintInfo(struct PersonInfo per)
{
printf("%s %d %s %f\n", per.name, per.age, per.sex, per.height);
}
int main()
{
struct PersonInfo p = {"鲍鱼", 30, "男", 169.5};
PrintInfo(p);
return 0;
}
传值操作会有较大的压栈开销,时间和空间效率比较低下
2、传址操作:
#include<stdio.h>
struct PersonInfo
{
char name[10];
int age;
char sex[3];
float height;
};
void PrintInfo(struct PersonInfo *per)
{
printf("%s %d %s %f\n", per->name, per->age, per->sex, per->height);
}
int main()
{
struct PersonInfo p = {"鲍鱼", 30, "男", 169.5};
PrintInfo(&p);
return 0;
}
传址操作无论结构体有多大,都只需传递一个指针大小,时间和空间效率很高。
八、总结
团队合作力量是无穷的,结构体就是那一贴粘合剂。
九、作业
CC13 KiKi定义电子日历类
#include <stdio.h>
struct Date
{
int year;
int month;
int day;
};
int main()
{
struct Date dt;
scanf("%d %d %d", &dt.year, &dt.month, &dt.day);
printf("%d/%d/%d", dt.day, dt.month, dt.year);
return 0;
}
CC16 牛牛的平面向量
#include <stdio.h>
struct Point
{
int x;
int y;
};
int main()
{
int n;
scanf("%d", &n);
struct Point p[n];
for(int i=0; i<n; ++i)
scanf("%d %d", &p[i].x, &p[i].y);
int sum_x=0, sum_y=0;
for(int i=0; i<n; ++i)
{
sum_x += p[i].x;
sum_y += p[i].y;
}
printf("%d %d", sum_x, sum_y);
return 0;
}
CC15 牛牛的书
#include <stdio.h>
struct BookInfo
{
char name[20];
int price;
};
int main()
{
int n;
scanf("%d", &n);
struct BookInfo book[n];
for(int i=0; i<n; ++i)
{
scanf("%s %d", book[i].name, &book[i].price);
}
for(int i=0; i<n-1; ++i)
{
for(int j=0; j<n-1-i; ++j)
{
if(book[j].price > book[j+1].price)
{
struct BookInfo tmp = book[j];
book[j] = book[j+1];
book[j+1] = tmp;
}
}
}
for(int i=0; i<n; ++i)
printf("%s\n", book[i].name);
return 0;
}