zoukankan      html  css  js  c++  java
  • C语言基础07

    结构体与函数的区别:

      1.函数是由相同数据类型的变量组成.

      2.结构体可以有不同数据类型组合。可以包含char,int,float,数组等类型.

    struct 结构名称 {

      数据类型 成员   注意必须是以分号隔开

      ...

    };

    //创建一个构造体

    struct student {

      int age;

      char name[45];

      char gender;

      float score;

    };

      // 创建结构体变量同时为其赋值

    struct student stu ={18,"luoshuai",'m',87,5};        

    但是:struct student stu1;

    stu1={18,"luoshuai",'m',87,5}; 

    // 报错,如果在声明的时候,没有全部赋值,不可以再在后面进行全部赋值。

    但是可以逐个的赋值

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

    struct student stu1;

    stu1.age =18;

    // stu1.name= "lihuahua";   字符串数组 或者数组都不能相互之间直接赋值使用函数。

    strcpy(stu1.name,"luohuahua");

    typedef   重命名。可以简化系统的数据类型名称

    typedef int  Integer;

    Integer score = 98;

    //typedef和结构体组合使用,后面经常使用

    typedef struct {

      int age;

      char name[30];

      char gender;

      float weight;

    } Cat ;

    // 结构体的嵌套

    typedef struct{

      int year ;

      int mouth;

       int day;

    } Birthday;

    typedef struct{

      int age;

      char name[30];

      Birthday bir;

    } People;

    People p1 = {"jiesi",29847901093,{1990,6,12}};

    printf("%d ",p1.bir.year);

    注意,字符串数组或者数组都不能直接赋值给其他变量。

    但是结构体相互之间是可以的。所以如果你想交换数组,可以使用结构体。

    typedef  struct {

       int age;

       float weight;

       char arr[34];

        } Baby;

        Baby ba1 = {1,23.5,{"myname","lover"}};

      Baby ba2 ={};    //一个空得结构体变量

       ba2 =ba1;

       printf("ba2:%d",ba2.age);  // 1

    typedef struct {

      int age;         4字节

      double score ;   8字节

      char gender;     1字节

      char name[20];   20字节

    } Student;

    在面试中我们会遇到计算struct在内存占的空间,上面已经列出每个变量的内存字节占用,相加33个.

    以最大的成员变量数据类型为单位,这里是Double的8字节最大,然后 8 * n >=  33 , n取值5才能满足,所以内存占用5*8=40个字节。

     

    有五个学生,编程找出分数最高者:

    typedef struct{

      int num;

      char name[50];

      float score;

      char gerder;

    } Student;

     Student stu ={

      {23,"luoshuai",78.3,'m'},

      {51,"luoting",98.5,'m'},

      {76,"luoteng",23.6,'w'},

      {96,"liruoxuan",67.9,'w'},

    }; 

    int count =sizeof(stu) / sizeof(Student);

    for(int i = 0 ;i < count-1 ; i++){  

      for (int j =0 ; j < count-i-1 ;j++){

          if( stu[j].score >  stu[j+1].score){

           //交换的是结构变量数组元素,不是里面的分数 temp是结构变量

             Student temp =  stu[j].score;

             stu[j].score = stu[j+1].score;

             stu[j+1].score = tem;

          }

      }

      printf("信息为%s,分数为%f ",scores[i].name,scores[i].score);

    }

  • 相关阅读:
    css属性设置
    自由从摇篮开始 ——杨支柱
    提醒幸福
    随记
    那些回不去的年少时光(桐华)
    Javascript 与正则表达式
    XmlHttpRequest对象的获取及相关操作
    CSS的4种引入方式及优先级
    c#textBox控件限制只允许输入数字及小数点,是否为空
    c# 循环界面控件
  • 原文地址:https://www.cnblogs.com/liruoxuan/p/4077468.html
Copyright © 2011-2022 走看看