您的位置:首页 > 其它

typedef struct用法总结_20150827

2015-08-27 23:03 232 查看
***关于C中结构体重定义typedef struct那点儿事***


typedef的字面意思是类型定义,也即重命名。例如

typedef unsigned int uint    //以后凡是用到unsigned int的地方都可以用uint代替
typedef struct node Node    //以后声明结构体变量便可以直接写Node stu1,当然也可以写struct node stu1


区别仅在于是否可以省略struct这个结构体类型关键字

1、结构体类型struct

在C中声明结构体类型要使用

struct 结构体名
{
类型1 成员1;
类型2 成员2;
...
};


比如

struct Student
{
char name[20];
int Id;
};


以后声明这种类型的结构体变量时需要这样写:

Struct Student stu1, stu2;


也可以在声明类型的同时,声明结构体变量,如下

struct Student
{
char name[20];
int Id;
}stu1, stu2;


2、使用typedef定义类型名

typedef的一般形式为typedef 原类型名 新类型名; 对于结构体类型除了可以为已定义的结构体类型起新的名字外,也可以在定义结构体类型的同时为其声明新的名字,用法如下

typedef struct Student
{
char name[20];
int Id;
}STU;
这样以后声明变量时可以直接写STU stu1;


3、陷阱

struct Student
{
char name[20];
int Id;
}stu1;      //stu1是一个变量,使用时可以直接访问 stu1.Id=001;

typedef struct Student
{
char name[20];
int Id;
}stu2;      //stu2是一个结构体类型,使用时必须先声明变量 stu2 s;  然后才能访问变量的成员s.Id=002;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: