https://www.sharetechnote.com/html/C_typedef.html
typedef是一个关键字,通过它可以将现有的数据类型的名称重命名为另一个更有意义或更方便的名称。如果你在别人的代码中看到任何不像C语言默认(本地)数据类型的数据类型名称(通常是全部大写),那么很可能这些是使用typedef关键字标记的现有(本地)数据类型的新名称。
typedef用于值
typedef用于结构体
Example 01 >
#include <stdio.h>
typedef unsigned int POSITIVEINT; // rename (redefine) the type 'unsigned int' into the new name POSITIVEINT
typedef unsigned char BYTE; // rename (redefine) the type 'unsigned char' into the new name BYTE
typedef unsigned char* STRING; // rename (redefine) the type 'unsigned char*' into the new name STRING
void main()
{
POSITIVEINT a = 100;
BYTE b = 100;
STRING str = "Hello World !";
printf("Size of POSITIVEINT = %d, Value of POSITIVEINT a = %d\n",sizeof(a),a);
printf("Size of BYTE = %d, Value of BYTE b = %d\n",sizeof(b),b);
printf("Value of STRING str = %s\n",str);
}
Result :------------------------------------
Size of POSITIVEINT = 4, Value of POSITIVEINT a = 100
Size of BYTE = 1, Value of BYTE b = 100
Value of STRING str = Hello World !
typedef for struct =============================================
Example 01 >
#include <stdio.h>
typedef struct POINT {
float x;
float y;
} Point;
int main()
{
Point pt;
pt.x = 1.2;
pt.y = 2.1;
printf("The coordinate of pt is = (%f,%f)", pt.x, pt.y);
return 1;
}
Result :
The coordinate of pt is = (1.200000,2.100000)
Example 02 >
#include <stdio.h>
struct POINT {
float x;
float y;
};
typedef struct POINT Point;
int main()
{
Point pt;
pt.x = 1.2;
pt.y = 2.1;
printf("The coordinate of pt is = (%f,%f)", pt.x, pt.y);
return 1;
}
Result :
The coordinate of pt is = (1.200000,2.100000)
Example 03 >
#include <stdio.h>
typedef struct{
float x;
float y;
} POINT;
typedef POINT Point;
int main()
{
Point pt;
pt.x = 1.2;
pt.y = 2.1;
printf("The coordinate of pt is = (%f,%f)", pt.x, pt.y);
return 1;
}
Result :
The coordinate of pt is = (1.200000,2.100000)
Example 04 >
#include <stdio.h>
#include <malloc.h>
typedef struct POINT {
float x;
float y;
} Point;
int main()
{
Point *pt;
pt = (Point*) malloc(sizeof(Point));
pt->x = 1.2;
pt->y = 2.1;
printf("The coordinate of pt is = (%f,%f)", pt->x, pt->y);
return 1;
}
Result :
The coordinate of pt is = (1.200000,2.100000)

被折叠的 条评论
为什么被折叠?



