如何使用指针对结构数组进行排序?

时间:2018-12-18 05:43:31

标签: c arrays sorting structure

编写程序向结构数组输入id,名称和地址,并使用指针根据名称将它们按升序排序吗?

我尝试在这个论坛中搜索很多问题,但是没有一个问题能帮助我。这是我的代码:

 #include<stdio.h>
struct student
{
    char name[20], add[30];
    int id;
};
int main()
{
    struct student s[100];
    struct student *sptr;
    int i, j, temp, n;
    char tempc[30];
    sptr=&s;
    printf("How many students do we have to register?");
    scanf("%d",&n);
    printf("Enter the id, name and address of the students and hit enter.");

    for (i=0; i<n; i++)
    {
        scanf("%d%s%s",&sptr->id,&sptr->name,&sptr->add);
        sptr++;
    }
    sptr=&s;
    for(i=0; i<n; i++)
    {
        for(j=i+1;j<n;j++)
        {
            if(strcmp(s[i].name,s[j].name)>0)
            {
                strcpy(tempc,(sptr+i)->name);
                strcpy(sptr->name,(sptr+j)->name);
                strcpy((sptr+j)->name,tempc);
                strcpy(tempc,sptr->add);
                strcpy(sptr->add,(sptr+j)->add);
                strcpy((sptr+j)->add,tempc);
                temp=(sptr+j)->id;
                sptr->id=(sptr+j)->id;
                (sptr+j)->id=temp;

            }
        }
    }
    printf("The sorted form is:");

     for (i=0; i<n; i++)
    {
        printf("%d%s%s",sptr->id,sptr->name,sptr->add);
        sptr++;
    }



}

如果您要去我要去的地方,请帮帮我。是的,我不想使用任何内存分配函数或sizeof()函数。

1 个答案:

答案 0 :(得分:1)

只需使用qsort,如下所示:

int compare_student (const void * a, const void * b)
{

  struct student *lhs = (struct student *)a;
  struct student *rhs = (struct student *)b;

  return strcmp( lhs->name, rhs->name) ;
}

// N = total number of students;

qsort (s, N, sizeof(struct student), compare_student);