5

如何在C语言中定义自己的数据类型?

 2 years ago
source link: https://blog.51cto.com/u_15340774/5526624
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
如何在C语言中定义自己的数据类型?_共用体

在C语言编程中,我们其实可以打开编程语言的拘束,自己定义自己想要的数据类型。只要记住 ​​struct​​ 和 ​​typedef​​ 两个关键词,我们就可以通过C语言中的数据结构和共用体来保存非同质化的数据类型。

定义新的数据类型

首先,在​ ​C语言在线编译器​​中输入以下代码:

typedef struct student_structure {
char* name;
char* surname;
int year_of_birth;
} student;

完成后,这段代码会把 ​​student​​ 预存为保留词,那样我们能创建 ​​student​​ 类型的变量了。

那么这个新变量究竟是怎样构成的呢?

我们所创建的这个结构化新变量是通过一系列基础变量组成的。在上面的代码中,我们把 ​​char* name​​、​​char* surname​​ 这些变量组成了新的 ​​student​​ 变量中,其实就是放到内存块的一个名下。

使用新数据类型

我们现在创建好新的 ​​student​​ 变量后,可以在​ ​C语言在线编译器​​中为它初始化一些属性:

student stu;

strcpy(stu.name, "John");
strcpy(stu.surname, "Snow");
stu.year_of_birth = 1990;

printf("Student name : %s\n", stu.name);
printf("Student surname : %s\n", stu.surname);
printf("Student year of birth : %d\n", stu.year_of_birth);

在上面的例子中,眼尖的你可能已经发现了我们需要为新数据类型的所有变量分配一个值。除了使用 ​​stu.name​​ 来访问外,我们还可以使用更短的方式来为这些结构分配值:

typedef struct {
int x;
int y;
} point;

point image_dimension = {640,480};

你也可以使用不同的顺序来设定值:

point img_dim = { .y = 480, .x = 640 };

共用体 vs 结构

共用体(Union)的说明方式与 ​​struct​​ 相同,但他们却不太一样。在共用体中,我们只可以使用同一种类型的数据。像这样:

typedef union {
int circle;
int triangle;
int ovel;
} shape;

只有在数据类型相同的情况下,才会使用 ​​union​​。我们可以在​ ​C语言在线编译器​​中尝试一下我们的新数据类型:

typedef struct {
char* model;
int year;
} car_type;

typedef struct {
char* owner;
int weight;
} truck_type;

typedef union {
car_type car;
truck_type truck;
} vehicle;

其他小技巧

  • 当我们使用​​&​​ 运算符为结构创建一个指针时,我们也可以使用特殊的​​->​​ inflix运算符来进行表达。
  • 在​ ​C 语言在线编译器​​中,我们甚至可以像基础的数据类型那样任意使用我们的新数据类型。
  • 我们可以复制或指定​​struct​​ 的值,但我们不能对它们进行对比!

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK