C语言提供了基本的数据结构,例如 char 、short 、int 、float....等类型;这些偶称为内置类型。怎样设计出来属于自己的类型?
比如:当我们定义一个人的时候,人的不同属性就比较难用同一个数据类型来定义了,因为人的身高、年龄、体重等属性往往需要不同数据类型,在这个时候,我们便引入结构体这个概念
使用结构体来封装一些属性,设计出新的类型,在C语言中称为结构体类型。结构是一些值的集合,这些值称为成员变量。结构的每个成员可以是不同类型的变量
结构声明(structure declaration)
- struct 结构体名
- {
- 成员列表(可以是基本的数据类型,指针,数组或其他结构类型)
- };
- /*struct关键词表示接下来是一个结构。*/
- struct People
- {
- char s_id[8];
- char s_name[8];
- char s_sex[4];
- int s_age;
- };
注意;
结构体的声明只是进行一个简单的描述,实际上在没有定义结构体类型变量之前,它是不会在内存中分配空间的。
- int main()
- {
- struct People people;//局部变量--放在栈区
- return 0;
- }
* struct 结构体名称 结构体变量名
结构体是一种数据类型,也就是说可以用它来定义变量。就像一个“模板”,定义出来的变量都具有相同的性质。可以将结构体比作“图纸”,结构体变量比作“零件”,根据同一张图纸生产出来的零件的特性都是一样的;
- #include<stdio.h>
- #include<string.h>
- struct Date
- {
- int year;
- int month;
- int day;
- };
- struct Student
- {
- char s_name[20];
- struct Date birthday;
- float score;
- };
- int main()
- {
- struct Student stu = { "liuwen",2000,10,1,99.9 };
- printf("name=%s\nbirtyday=%d.%d.%d\nscore=%f\n", stu.s_name, stu.birthday.year, stu.birthday.month, stu.birthday.day, stu.score);
- stu.score = 77;
- printf("name=%s\nbirtyday=%d.%d.%d\nscore=%f\n", stu.s_name, stu.birthday.year, stu.birthday.month, stu.birthday.day, stu.score);
- return 0;
注意:对结构体变量整体赋值有三种情况
在C语言中不存在结构体类型的强制转换。
内置类型可以定义指针变量,结构体类型也可以定义结构体类型指针;
结构体类型指针访问成员的获取和赋值形式:
(1)(*p). 成员名(.的优先级高于*,(*p)两边括号不能少)
(2) p->成员名(->指向符)
- #include<stdio.h>
- #include<string.h>
- struct Inventory//商品
- {
- char description[20];//货物名
- int quantity;//库存数据
- };
- int main()
- {
- struct Inventory sta = { "iphone",20 };
- struct Inventory* stp = &sta;
- char name[20] = { 0 };
- int num = 0;
- (*stp).quantity = 30;
- stp->quantity = 30;
- strcpy_s(name,sizeof(stp->description),stp->description);
- printf("%s %d\n", stp->description, stp->quantity);
- printf("%s %d\n", (*stp).description, (*stp).quantity);
- return 0;
- }
结构体和函数
- #include<stdio.h>
- #include<string.h>
- #define _CRT_SECURE_NO_WARNINGS
- struct School
- {
- char s_name[20];//学校
- int s_age;
- };
- void Print_a(struct School sx)
- {
- printf("%s %d\n", sx.s_name, sx.s_age);
- }
- void Print_c(struct School* sp)
- {
- printf("%s %d\n", sp->s_name, sp->s_age);
- }
- int main()
- {
- struct School sx = { "xi'an",100 };
- Print_a(sx);
- Print_c(&sx);
- return 0;
- }
1、什么是class?
class(类)是面向对象编程的基本概念,是一种自定义数据结构类型,通常包含字段、属性、方法、属性、构造函数、索引器、操作符等。因为是基本的概念,所以不必在此详细描述,读者可以查询相关概念了解。我们重点强调的是.NET中,所有的类都最终继承自System.Object类,因此是一种引用类型,也就是说,new一个类的实例时,对象保存了该实例实际数据的引用地址,而对象的值保存在托管堆(managed heap)中。
2、什么是struct?
struct(结构)是一种值类型,用于将一组相关的信息变量组织为一个单一的变量实体。所有的结构都继承自System.ValueType类,因此是一种值类型,也就是说,struct实例分配在线程的堆栈(stack)上,它本身存储了值,而不包含指向该值的指针。所以在使用struct时,我们可以将其当作int、char这样的基本类型类对待。