您的位置:首页 > 其它

结构体

2015-10-23 15:34 239 查看
(1)结构体:结构体是一种自定义的数据类型

struct  结构体名

{

类型说明符  成员名;

..........

类型说明符  成员名;

}

结构体变量的定义:由结构体类型修饰的变量叫结构体变量;

           struct   结构体名  变量名 = {初值};

例如  {*****上面定义******

struct student1
{
   int num;         
//学号
   char name[20];  
//姓名
   char sex;      
//性别
   float score;  
//分数
};
**************
}

 struct     student    Ferrari = {1,"Ferrari",'m',99};

(上面定义,下面输出)

结构体成员的访问.成员变量名

输出:structstudent1 Ferrari={1,"Ferrari",'m',99.9};

(发现可以重复输出,structstudent1
Ferrari={1,"Ferrari",'m',99.9};



(2)匿名结构体:结构体的声明与变量的定义组合在一起

//        例如:

        /*   struct{

         int num;          //学号

         char name[20];   //姓名

         char sex;       //性别

         float score;   //分数

         }

     */

//匿名结构体输出
       
/*

         printf("stu1.k=%d\n",stu1.k);

         printf("stu1.kk=%f\n",stu1.kk);

         */
*********
(上面的定义)

struct

//{int k;

//    float kk;

//    char l;

//    double ll;

//

//}

//stu1={5000,0.618,'g',3.141592};

***********
(3)typedef,为现有类型创建一个类型别名

语法:typedef  原类型名, 新类型名

(例)#########

typedef float fudian;
       
fudian a=3.1415;
       
printf("a=%.3f\n",a);

        

        
       
typedef int zx;
       
zx b=5000;
       
printf("b=%d\n",b);
#############

结构体成员依然可以是结构体(用的不多)

……………………………………

typedef struct data{

         int year;

         int month;

         int day;

         }MyDate;

         typedef struct student3{

         char name[20];

         MyDate birthday;

         }Student3;

         

         Student3 stud1={"BenZ",{1999,12,5}};

         printf("stud1.birthday.year=%d\n",stud1.birthday.year);

         printf("stud1.birthday.month=%d\n",stud1.birthday.month);

         printf("stud1.birthday.day=%d\n",stud1.birthday.day);
…………………………………………

 //结构体数组“将多个结构体放到数组中。例如

        //  struct  student students [10]={赋值};

例题:

//  输出最大成绩和全部信息
       typedef  
struct student001{
           char name[15];
           int num;
           char sex;
           int score;
        }Student01;

        
       Student01 k[5]={{"monse",1,'a',90},{"monkey",8,'a',99},{"mon",10,'a',88},{"monk",11,'a',77},{"monke",22,'a',66}};
       int max=0;
       for (int i=0; i<4; i++) {
           if (max<k[i].score) {
                max=k[i].score;
            }
        }
       printf("%d\n",max);
       for (int i=0; i<4; i++) {

            

        
       if (max==k[i].score) {
           printf("%s\n %d\n %c\n %d\n",k[i].name,k[i].num,k[i].sex,k[i].score);
        }
        }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: