typedef的全部用法
本帖最后由 wanduzi 于 2025-9-3 22:47 编辑1. 基本类型别名
typedef int Integer;
typedef float Real;
typedef char Byte;
Integer age = 25; // 实际是 int
Real salary = 5000.50; // 实际是 float
Byte data = 'A'; // 实际是 char
2. 数组类型别名
typedef int Vector; // Vector 是 int 的别名
typedef float Matrix; // Matrix 是 float 的别名
Vector v = {1, 2, 3}; // 相当于 int v = {1, 2, 3};
Matrix m; // 相当于 float m;
3. 指针类型别名
typedef int* IntPtr;
typedef char* String;
IntPtr p = NULL; // 相当于 int* p = NULL;
String name = "John"; // 相当于 char* name = "John";
4. 结构体别名
// 方式1:先定义结构体,再typedef
struct Point {
int x;
int y;
};
typedef struct Point Point;
// 方式2:定义时直接typedef
typedef struct {
int x;
int y;
} Point;
// 使用
Point p1 = {10, 20}; 5. 联合体别名
typedef union {
int i;
float f;
char c;
} Variant;
Variant v;
v.i = 100; 6. 避免重复struct关键字
// 没有typedef
struct Person person1;// 需要struct关键字
// 有typedef
typedef struct {
char name;
int age;
} Person;
Person person2;// 不需要struct关键字 7. 基本函数指针
typedef int (*Comparator)(int a, int b);
int compare_asc(int a, int b) { return a - b; }
int compare_desc(int a, int b) { return b - a; }
Comparator comp = compare_asc;
int result = comp(5, 3);// 返回 2 8.复杂函数指针
// 返回函数指针的函数
typedef int (*MathFunc)(int, int);
typedef MathFunc (*GetOperation)(char op);
MathFunc get_add_function() { return add; }
GetOperation op_getter = get_add_function; 9.回调函数
typedef void (*Callback)(int status, const char* message);
void process_data(Callback callback) {
// 处理数据...
callback(0, "处理完成");
}
void my_callback(int status, const char* msg) {
printf("状态: %d, 消息: %s\n", status, msg);
}
process_data(my_callback); 类型组合
typedef int* IntArrayPtr;
typedef IntArrayPtr* IntMatrixPtr;
IntArrayPtr arr = malloc(10 * sizeof(int)); // int*
IntMatrixPtr mat = malloc(5 * sizeof(int*)); // int** 平台无关类型
// 确保在不同平台上有相同的大小
typedef signed char int8_t;
typedef short int16_t;
typedef int int32_t;
typedef long long int64_t;
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;
typedef unsigned long long uint64_t; 复杂类型解析
typedef int (*ArrayOfFuncPtrs)(void);
// 解析:ArrayOfFuncPtrs 是包含10个函数指针的数组类型
// 每个函数指针指向返回int且无参数的函数
ArrayOfFuncPtrs funcs;
funcs = some_function;
页:
[1]