c中结构体排序

#include <stdio.h>
#include <malloc.h>
#include <string.h>


struct student
    {
        char name[10];
        int score;
    };
void sort(struct student *ptr,int n);
void main()
{

    struct student *ptr;
    int n , i;
    //printf("Please enter n:");
   // scanf("%d",&n);
    ptr=(struct student *)malloc(n*sizeof(struct student));
    for(i=1;i<6;i++)
    {   printf("请输入第 %d 个学生的姓名 分数",i);
        scanf("%s %d",&ptr[i-1].name,&ptr[i-1].score);
    }
    sort(ptr,5);
    for(i=0;i<5;i++)
    {
        printf("%s %d\n",ptr[i].name,ptr[i].score);
    }
    getch();
}
void sort(struct student *ptr , int n)
{
     char name_tmp[10];
     int i , j ,tmp;
     for(i=0;i<n;i++)
        for(j=0;j<n-1;j++)
        {
           if(ptr[j].score<ptr[j+1].score)
           {
             tmp=ptr[j].score;
             ptr[j].score=ptr[j+1].score;
             ptr[j+1].score=tmp;
             strcpy(name_tmp,ptr[j].name);
             strcpy(ptr[j].name,ptr[j+1].name);
             strcpy(ptr[j+1].name,name_tmp);
           }
       }
}

你可能感兴趣的:(结构体)