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

sorting structures with name not working in C

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;
}

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

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

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