zoukankan      html  css  js  c++  java
  • c语言中结构体数组

    c语言中的结构体数组(数组元素为结构体)。

    1、

    #include <stdio.h>
    #include <string.h>
    
    #define NUMBER 5
    #define NAME_LEN 64
    
    typedef struct{
        char name[NAME_LEN];
        int height;
        float weight;
        long schols;
    }Student;
    
    void swap(Student *x, Student *y) // 结构体交换函数 , 形参为Student型的结构体对象指针 
    {
        Student tmp = *x;
        *x = *y;
        *y = tmp;    
    } 
    
    void sort(Student x[], int n)
    {
        int i, j;
        for(i = 0; i < n - 1; i++)
        {
            for(j = n - 1; j > i; j--)
            {
                if(x[j - 1].height > x[j].height) //排序的依据是结构体数组中的元素中的height结构体成员 
                {
                    swap(&x[j - 1], &x[j]);  //此处给与的实参应该是Student型的结构体对象的指针, 使用取址运算符获取结构体对象的指针 
                }
            }
        }
    }
    
    int main(void)
    {
        int i;
        Student stu[] = {  //此处为结构体数组, 数组的元素为结构体,结构体对象的类型为Student。 
        {"Sato",178,61.2,80000},
        {"Sanaka",175,62.5,73000},
        {"Takao",173,86.2,0},
        {"Mike",165,72.3,70000},
        {"Masaki", 179, 77.5,70000},
        };
        for(i = 0; i < NUMBER; i++)
        {
            printf("%-8s %7d%7.2f%7ld
    ", stu[i].name, stu[i].height,stu[i].weight,stu[i].schols);
        }
        sort(stu, NUMBER);
        puts("
    =====================================
    ");
        for(i = 0; i < NUMBER; i++)
        {
            printf("%-8s %7d%7.2f%7ld
    ", stu[i].name, stu[i].height,stu[i].weight,stu[i].schols);
        }
        return 0;
    }

  • 相关阅读:
    MFC Windows 程序设计>WinMain 简单Windows程序 命令行编译
    AT3949 [AGC022D] Shopping 题解
    CF643D Bearish Fanpages 题解
    CF643C Levels and Regions 题解
    CF241E Flights 题解
    CF671C Ultimate Weirdness of an Array 题解
    CF1592F Alice and Recoloring 题解
    GYM 102452E 题解
    CF494C Helping People 题解
    P5556 圣剑护符
  • 原文地址:https://www.cnblogs.com/liujiaxin2018/p/14852532.html
Copyright © 2011-2022 走看看