您的位置:首页 > 编程语言 > C语言/C++

C语言基础(九)结构体、补充typedef用法

2015-10-26 22:47 531 查看
1、作用:一个变量可以保存多个不同类型的数据
2、定义结构体的语法:
     struct 结构体名
     {
          成员列表;
     };
     例:struct student{
          int stuNo;
          char name[50];
          }
注意:上面的语法只是定义一个新的类型,而这个类型叫做结构体类型,不是定义了一个变量
3、定义结构体的变量:
     struct 结构体名 变量名;     例:str student stu1;
     赋值语法:
     变量名.成员 = 数据;     例:stu1.stuNo = 1;
4、输出:没有格式化控制符能够一下子输出整个结构体,必须一个一个输出
      例:printf(“stuNo=%d name=%s”,stu.stuNo,stu.name);
5、初始化:
     (1)先声明,后赋值:见3
     (2)在声明的时候初始化
               struct 结构体名 变量名 = {数据1,数据2...数据N};
               例:struct student stu1 = {1,”zhangsan”};
     (3)先声明,后一次性赋值
               sturct 结构体名 变量名;
               变量名 = (struct 结构体名) = {数据1,数据2...数据N};
               例:struct studeng stu1;
                      stu1 = (struct student){1,”zhangsan”};
6、特殊用法:
     (1)在结构体大括号后面写标志符,就是定义它的变量,也可以定义多个,用“,”隔开
     (2)结构体名可以省略,叫做匿名结构体。匿名结构体的变量只能在声明的时候定义
     (3)结构体变量之间赋值都是值传递
     (4)结构体变量作为函数的参数也是值传递
7、结构体的嵌套
typedef struct

{

    int year;

    int month;

    int day;

}Date;
typedef struct

{

    char name[50];

    Date birth;

    int age;

    float height;

    float weight;

    char gender;

    int CScore;

    char figure;

}Student ;
int main(int argc, const char * argv[]) {
    Student stu={“逗比",{1994,8,21},21,1.81,69,'m',59,'S'};
    printf("姓名:%s  
生日:%d,%d,%d  
年龄:%d  
身高:%f  
体重:%f  
性别:%c   C语言成绩:%d   
身材:%c\n",stu.name,stu.birth.year,stu.birth.month,stu.birth.day,stu.age,stu.height,stu.weight,stu.gender,stu.CScore,stu.figure);

    return 0;
 }
注:以上代码使用了typedef,下面有提到
8、typedef补充
     (1)作用:给某个类型起别名
     (2)语法:typedef 类型名 别名     例:typedef int i;
     (3)应用在结构体中
               typedef struct stu
               {
                    成员变量;
               }student;
               此时,这个结构体的类型名就有了一个别名:student,在调用这个结构体类型时直接写student就可以了。即struct stu 等同于 student。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C语言