c 语言学习 之对于动态内存分配的结构体的基于交换的排序

/*

author : YangHongchao

day: 2018/4/23

*/


#include <stdio.h>

#include <string.h>
#include <stdlib.h>


struct student
{
    char name[12];
    int age;
    int score[3];
    double average;
};


typedef struct student student;


void swap (student *s1, student *s2)   //exchange struct
{
    student temp = *s1;
    *s1 = *s2;
    *s2 = temp;
}


int main()
{
    student s[4];
    int n;
    int i = 0, j = 0;
    student *pPrime;
    scanf("%d", &n);
    pPrime = (student *) malloc(sizeof(student)* n);   //dynamic assign struct array
    if (!pPrime)
    {
        printf(" Not enough memory. It's the end I'm afraid.\n");
        return 1;
    }
    printf("-----------------\n");
    printf("please input %d students: name[20], age[int], score[1], score[2], score[2], average.\n", n);
    for ( i = 0; i < n; i++)
        scanf("%s %d %d %d %d %fl", s[i].name, &s[i].age, &s[i].score[0], &s[i].score[1], &s[i].score[2],
              &s[i].average);
    for (i = 0; i < n; i++)                  // sort base  exchange
    {
        for (j = i + 1; j < n; j++)
        {
            if (s[i].score[0] < s[j].score[0])
                swap(&s[i], &s[2]);
            else if (s[i].score[0] == s[j].score[0])
            {
                if ( strcmp(s[i].name, s[j].name) > 0)
                    swap(&s[i], &s[j]);
            }
        }
    }
    for (i = 0; i < 3; i++)
        printf("name = %s, age = %d, \n", s[i].name, s[i].age);
    free(pPrime);
    pPrime = NULL;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Modern_Times/article/details/80048437