text 使用Typedef为结构数据类型提供较短的名称

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了text 使用Typedef为结构数据类型提供较短的名称相关的知识,希望对你有一定的参考价值。

The C keyword "typedef" provides a way to create a shorthand or rewritten name for data types. So if the original data type name are 2 words, it's a bit long and not convenient if we use it a lot. So we would use "typedef" to give it a one word shorter name.

typedef <old name> <new name>;

We can use "typedef" for the data types in C, give it a shorter name instead:

typedef unsigned char byte; // so here the original data type "unsigned char" will have a shorter name "byte". Much easier to use.

In cs50.h, we used "typedef" to define the data type "string":

typedef char* string;

Because all the custom data types have a "struct" before it, like "struct car", we often use "typedef" to give it a one word shorter name:

First we define it the normal way:

struct car
{
	int year;
	char model[10];
	char plate[7];
	int odometer;
	double engine_size;
};

Then we give it a shorter name:

typedef struct car car_t;

So now if we want to declare a new variable of this type, we can just write:

car_t mycar; // much easier

A more easier way to use "typedef" for structures is to define the new structure in the middle of "typedef":

typedef struct car
{
	int year;
	char model[10];
	char plate[7];
	int odometer;
	double engine_size;
}
car_t;


以上是关于text 使用Typedef为结构数据类型提供较短的名称的主要内容,如果未能解决你的问题,请参考以下文章

结构体中typedef语句用法总结

数据结构基础-结构体struct及类型别名typedef的使用

19-typedef

C++中typedef是啥意思啊

typedef struct LNode命名结构指针(线性表的链式存储)

typedef struct用法详解与小结