现在的位置: 首页 > 综合 > 正文

struct与typedef struct的区别

2013年11月23日 ⁄ 综合 ⁄ 共 896字 ⁄ 字号 评论关闭

 

struct{
成员表列
}变量名表列1,变量名表列2;
(变量名表列1,变量名表列2)这2个变量名怎么理解? 

一个是声明一个结构体的原始用法,
一个是把结构体取了个别名。

例如
struct list{
  int a;
  char c;
  stuct list *next;
};(注意这个分号不能少)

这个结构体的类型名是struct list ;struct只是声明结构体需要的关键字。 如果你要定义一个结构体变量 你就可以 :结构体类型 变量名
如:struct list student;

你是不是觉得写struct list 觉得很麻烦?
那你就可以把struct list起个别名;就是绰号
可以这样

struct list{
  int a;
  char c;
  stuct list *next;
};
typedef struct list A;
那么你的A student; 就等同与 struct list student;
。

当然你也可以在声明一个结构体的时候给它起别名
typedef struct list{
  int a;
char c;
struct list *next;
}A; 
//////////////////////////////////////////////////////////////////
(1) struct{ int x; int y; }test1; 
好,定义了 结构 test1,
test1.x 和 test1.y 可以在语句里用了。

(2) struct test {int x; int y; }test1; 
好,定义了 结构 test1,
test1.x 和 test1.y 可以在语句里用了。
与 1 比,省写 了 test

(3) 
typedef struct test 
{int x; int y;  // 你漏打分号,给你添上 
}text1,text2; 
只说了 这种结构 的(类型)别名 叫 text1 或叫 text2

真正在语句里用,还要写:
text1 test1;
然后好用 test1.x test1.y

或写 text2 test1;
然后好用 test1.x test1.y

(4)type struct {int x; int y; }test1;
这个不可以。
改 typedef ... 就可以了。
但也同 (3)一样,还要 写:
test1 my_st;
才能用 my_st.x 和 my_st.y 

抱歉!评论已关闭.