[英]Why doesn't this sorting function work? C
所以我有這個排序函數,假設接受一個結構數組,我需要按名稱組織它們,它們都有名字和姓氏,如果它們的姓氏相同,那么我必須轉到第一個名字比較一下。 所以我創建了2個字符串,其中包含最后和第一個名稱組合成1,然后我遍歷列表並查看哪個很小並將其向上移動。 但問題是......它什么也沒做......根本就不知道為什么!?
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;
}
}
}
}
誰知道什么是錯的?
buffer < buffer2
絕對不是你想要的。 那只是比較兩個內存地址! 您應該使用strcmp()
函數。 例如,
if (strcmp(buffer, buffer2) < 0)
您的功能應如下所示:
用於名稱比較
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;
}
}
}
}
用於名稱長度比較
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;
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.