Reputation:
I create a structure with 3 names,and I want to create a function that takes a structure (or a pointer to the structure) as parameter and sorts the names in alphabetical order. I don't know how to fix the sort_name
function, can anyone give me tips? Thanks in advance.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student {
char name[50];
};
void getDetail(struct student *ptr) {
int i;
for (i = 0; i < 3; i++) {
printf("Enter %dth name: " ,i+1);
scanf("%s", ptr->name);
ptr++;
}
}
void sort_name(struct student *ptr) {
int i,j=0;
char temp[50];
for (i=0;i<3;i++)
{
for (j=i+1;j<3;j++)
{
if(strcmp(ptr->name,(ptr+1)->name)>0)
{
strcpy(temp,ptr->name);
strcpy(ptr->name,(ptr+1)->name);
strcpy((ptr+1)->name,temp);
}
}
}
printf("In order:");
for(i=0;i<3;i++)
{
printf("%s",ptr->name);
}
}
int main()
{
struct student s[3];
getDetail(s);
sort_name(s);
return 0;
}
Upvotes: 0
Views: 56
Reputation: 311048
The function can look like
void sort_name(struct student *ptr) {
int i,j=0;
char temp[50];
for ( i=0; i<3; i++ )
{
for (j = 1; j < 3 - i; j++ )
{
if(strcmp(ptr[j-1].name,ptr[j].name ) > 0 )
{
strcpy( temp, ptr[j-1].name );
strcpy( ptr[j-1].name, ptr[j].name) ;
strcpy( ptr[j].name, temp );
}
}
}
}
Upvotes: 3