c语言结构体冒泡排序求教

2025-12-18 06:08:24
推荐回答(1个)
回答1:

struct Student
{
int ID;
char Name[10];
};

void sort(Student *a, int n)
{
Student t;
int i, j;
for(i=0;ifor(j=0;jif(a[j].ID>a[j+1].ID)
{
memcpy(&t, &a[j], sizeof(Student));
memcpy(&a[j], &a[j+1], sizeof(Student));
memcpy(&a[j+1], &t, sizeof(Student));
}
}
在结构体赋值中,上面使用memcpy函数,如:
memcpy(&t, &a[j], sizeof(Student));
可以替换为:
t.ID = a[j].ID;
strcpy(t.Name, a[j].Name);
依次类推。