Reputation: 391
So I have this sorting function that is suppose to take in an array of structs and I need to organize them by name, both have a first and last name and if their last names are the same then I must move on to the first name to compare as well. So I made 2 strings that contain the last and first name combined into 1, and I iterate through the list and see which is small and move it up. But the issue is...it doesnt do anything...at all, and I don't understand why!?
void sortStruct(struct student *list, int studentCount){
int j, k;
struct student temp;
char buffer[35];
char buffer2[35];
for (j = 0 ; j <= studentCount-2 ; j++){
sprintf(buffer, "%s, %s", list[j].lastname, list[j].firstname);
for(k = 1 ; k <= studentCount-1 ; k++){
sprintf(buffer2, "%s, %s", list[k].lastname, list[k].firstname);
if(buffer < buffer2){
temp = list[j];
list[j] = list[k];
list[j] = temp;
}
}
}
}
Anyone know whats wrong?
Upvotes: 2
Views: 133
Reputation: 24905
Your function should be like below:
For Name Comparison
void sortStruct(struct student *list, int studentCount)
{
int j, k;
struct student temp;
char buffer[35];
char buffer2[35];
for (j = 0 ; j <= studentCount-2 ; j++)
{
sprintf(buffer, "%s, %s", list[j].lastname, list[j].firstname);
for(k = 1 ; k <= studentCount-1 ; k++)
{
sprintf(buffer2, "%s, %s", list[k].lastname, list[k].firstname);
if(strcmp(buffer, buffer2)<0)
{
temp = list[j];
list[j] = list[k];
list[j] = temp;
}
}
}
}
For Name Length Comparison
void sortStruct(struct student *list, int studentCount)
{
int j, k;
struct student temp;
char buffer[35];
char buffer2[35];
for (j = 0 ; j <= studentCount-2 ; j++)
{
sprintf(buffer, "%s, %s", list[j].lastname, list[j].firstname);
for(k = 1 ; k <= studentCount-1 ; k++)
{
sprintf(buffer2, "%s, %s", list[k].lastname, list[k].firstname);
if(strlen(buffer)< strlen(buffer2))
{
temp = list[j];
list[j] = list[k];
list[j] = temp;
}
}
}
}
Upvotes: 2
Reputation: 2036
buffer < buffer2
is absolutely not what you want. That's just comparing two memory addresses! You should use the function strcmp()
. For example,
if (strcmp(buffer, buffer2) < 0)
Upvotes: 4