typedef 与结构体struct

1 struct

 struct 结构名
 { 
 	类型  变量名; 
	类型  变量名; 
      ... 
 } 结构变量;

1.1 定义结构体

(1)

struct Node{	
	int a;
}student;
// 访问
student.a = 10;

(2)

struct Node{
	...
};	
struct Node student;
// 访问
student.a = 10;

(3)

struct {	
	...
}student;
// 访问
student.a = 10;

注:

  • 只能用结构名(Node)创建实例,不能用 结构变量(student) 创建
    如,struct Node stu1; //允许,但struct student stu1; //不允许
  • (1)和(2)等价,(3)为 无名结构(一般在函数内部)

1.2 定义结构体 数组与指针

1.2.1 数组

(1)

struct Node{	
	...
}student[100];
// 访问
student[0].a = 10;

(2)

struct Node{
	...
};	
struct Node student[100];
// 访问
student[0].a = 10;

(3)

struct {	
	...
}student[100];
// 访问
student[0].a = 10;

1.2.2 指针

struct Node{	
	int a;
}*student, *students;
// 访问
student = (Node *)malloc(sizeof(Node));
student->a = 10;
(*student).a = 10;
students = (Node *)malloc(sizeof(Node)*100);	//指针数组
students[0]->a = 10;
(*students)[0].a = 10;

(2)

struct Node{
	...
};	
struct Node *student, *students;
// 访问
student = (Node *)malloc(sizeof(Node));
student->a = 10;
(*student).a = 10;
students = (Node *)malloc(sizeof(Node)*100);	//指针数组
students[0]->a = 10;
(*students)[0].a = 10;

2 typedef

2.1 定义变量

typedef int MY_INT;		// 给int起别名:MY_INT

int main(){
	MY_INT a = 100;		//相当于 int a = 100;
	return 0;
}

2.2 定义结构体

(1)

typedef struct Node{	//Node可省略变为(2)
	int a;
}Student;				// 给 Node 起别名 Student
//定义
Student stu;	// 第1种
stu.a = 10;
Node stu2;		// 第2种
stu2.a = 10;

(2)

typedef struct{		
	int a;
}Student;
//定义
Student stu;
stu.a = 10;

(3)

typedef struct Node{			// 由于成员中有struct Node *,因此 Node 不可省略
	int a;
	struct Node *deskmate;		
}Student;

2.3 定义结构体 数组与指针

2.3.1 数组

typedef struct Node{
	int a;
}Student, Stus[100];
//定义
Node stus1[100];		// 第1种
stus1[0].a = 10;
Student stus2[100];		// 第2种
stus2[0].a = 10;
Stus stus3;				// 第3种
stus3[0].a = 10;

2.3.2 指针

typedef struct Node{	
	int a;
}Student, *PStudent;
//定义
Student *pstu1;		// 第1种
pstu1 = (Student *)malloc(sizeof(Student));		//或 pstu1 = (Node *)malloc(sizeof(Node));	
pstu1->a = 10;
(*pstu1).a = 10;

PStudent pstu2;		// 第2种,PStudent pstu;  等价  Student *stu; 
pstu2 = (Student *)malloc(sizeof(Student));		//或 pstu2 = (Node *)malloc(sizeof(Node));	
pstu2->a = 10;
(*pstu2).a = 10;

3 成员访问小结

类型定义变量访问成员
结构型(定义1个)Student stu;stu.a
结构型(定义n个)Student stu[n];stu[i].a
指针型(定义1个)Student *stu;
stu = (Student *)malloc(sizeof(Student));
stu->a 或 (*stu).a
指针型(定义n个)Student *stu;
stu = (Student *)malloc(n * sizeof(Student));
stu[i]->a 或 (*stu)[i].a
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值