struct 和typedef struct的区别

一、结构体的定义

在C中定义一个结构体类型要用typedef:

typedef struct Student
 {
  int a;
 }Stu;
于是在声明变量的时候就可:Stu stu1;(如果没有typedef就必须用struct Student stu1;来声明)
这里的Stu实际上就是struct Student的别名。Stu==struct Student
另外这里也可以不写Student(于是也不能struct Student stu1;了,必须是Stu stu1;)
typedef struct
 {
    int a;

 }Stu;

二、结构体的初始化

/*结构体的赋值和初始化*/
 2 
 3 # include <stdio.h>
 4 
 5 struct Student 
 6 {
 7     int age;
 8     float score;
 9     char sex;
10 };
11 
12 int main(void)
13 {
14     struct Student st = { 80, 66.6, 'F'};//定义同时就赋值
15     struct Student st2;//下一行不能写一句类似于st2 = { 10, 88, 'M'};的语句,除非定义时就赋值。
16     st2.age = 10;
17     st2.score = 88;
18     st2.sex = 'M';
19 
20     printf("%d , %f, %c\n", st.age, st.score, st.sex);
21     printf("%d , %f, %c\n", st2.age, st2.score, st2.sex);
22 
23     return 0;
24 }
/*
26 在Vc++6.0中显示的结果是:
27 =========================================
28 80 , 66.599998, F
29 10 , 88.000000, M
30 =========================================
31 */

 如何取出结构体变量中的每一个成员
 3 */
 4 # include <stdio.h>
 5 
 6 struct Student 
 7 {
 8     int age;
 9     float score;
10     char sex;
11 };
12 
13 int main(void)
14 {
15     struct Student st = { 80, 66.6F, 'F'};
16     printf("age = %d\n",st.age);
17 
18 
19     struct Student * pst = &st;//&st不能改成st
20     pst->age = 88;  //第二种方式。。。pst->age在计算机内部,会被转化成(*pst).age 这是一种硬性规定
21                     //所以pst->age等价于(*pst).age ,也等价于st.age
22     printf("age = %d\n",st.age);
23 
24 
25     st.age = 10;  //第一种方式
26     printf("age = %d, score = %f\n",st.age, pst ->score);//st.age可写成pst ->age, pst ->score也可写成st.score.
27 
28     return 0;
29 }
30 /*
31 在Vc++6.0中显示的结果是:
32 ==============================================================
33 age = 80
34 age = 88
35 age = 10, score = 66.599998
36 ==============================================================
37 */








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值