------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
一.基本概念
给已经存在的数据类型取一个新的名字
二.使用场合
1.基本数据类型
typedef int MyInt; //给int取一个新的名字,MyInt相当于int
typedef MyInt MyInt2 //给MyInt取一个新的名字
//定义变量有3中方式
int a;
MyInt a;
MyInt2 a;
//以上三种方式都是定义一个整形变量a
2.指针
#include
typedef char * String; // 给char *起一个新的名字String
int main()
{
String name = "hello";
printf("%s\n", name); // 输出:hello
return 0;
}
3.结构体
// 方式一
struct PersonType {
char *name;
};
typedef struct PersonType Person;
// 方式二
typedef struct StudentType {
char *name;
} Student;
// 方式三
typedef struct{
char *name;
} Cat;
int main()
{
// 方式一
Person p = {"hello"};
printf("%s\n", p.name); // 输出:hello
// 方式二
Student stu = {"world"};
printf("%s\n", stu.name); // 输出:world
// 方式三
Cat cat = {"world"};
printf("%s\n", cat.name); // 输出:world
return 0;
}
4、指向结构体的指针
#include
struct Person {
char *name;
};
typedef struct Person * PersonPoint;
int main()
{
struct Person p = {"hello"};
PersonPoint pp = &p;
pp->name = "world";
printf("%s\n", p.name);
return 0;
}
5、枚举
#include
/*
// 方式一
enum SexEnum {
Man, Woman, Unknow
};
typedef enum SexEnum Sex;
// 方式二
typedef enum SexEnum {
Man, Woman, Unknow
} Sex;
*/
// 方式三
typedef enum {
Man, Woman, Unknow
} Sex;
int main()
{
Sex sex = Man;
printf("%d\n", sex);
return 0;
}
6、指向函数的指针
#include
int sum(int v1, int v2) //定义了一个函数
{
return v1 + v2;
}
typedef int (*IntFunc)(int, int); //定义了*IntFunc 这个类型,用这个类型的定义
的指针所指向的函数,这个函数接受两个参数,
参数的类型是int,并且返回值是int
int main()
{
IntFunc func = sum;
printf("%d\n", func(3, 4));
return 0;
}
三、#define与typede
#define String char *
typedef char * String2;
int main()
{
String s1 = "hello";
String2 s2 = "world";
printf("%s, %s\n", s1, s2);
return 0;
}
hello, world
#include
#define String char *
typedef char * String2;
int main()
{
String s1, s2;
String2 s3, s4;
return 0;
}
出行这种情况的原因
String2 s3, s4; typedef 是给类型起一个别名,所以就等于 char *s3; char *s4; 所以s3, s4都是char *类型的。