排序结构名称在C中不起作用

问题描述 投票:0回答:1
for(int i=0;i<numberOfStudents;i++){
        for(int j=i+1;j<numberOfStudents;j++){
            if (strcmp(newStudent[i].name,newStudent[j].name)>0){

                temp1=newStudent[i];
                newStudent[i]=newStudent[j];
                newStudent[j]=temp1;


            }


        }
    }

当我尝试运行此代码时,一切正常,但newStudent保持不变或未排序。

其中struct Student* newStudent = retrieve(filename, numberOfStudents);

也检索函数定义是

struct Student* retrieve(const char* filename, int numberOfStudents) {

    static struct Student temp[25];
    FILE* fp;
    fp = fopen(filename, "r");
    if(fp==NULL){
        printf("error occured while reading from the file\n");
    }
    for (int i = 0; i < numberOfStudents; i++) {
        fread(&temp[i], sizeof(struct Student), 1, fp);
    }
    fclose(fp);
    return temp;
}

我找不到错误代码。程序显示没有错误,唯一的问题是输出未排序

c sorting structure
1个回答
0
投票

您在内部循环中的交换是错误的。您可以用其原始值覆盖newStudent[i],而不是交换它们。它应该看起来像:

© www.soinside.com 2019 - 2024. All rights reserved.