在C语言中,要对结构体数组进行逆序排序,你可以使用以下方法:
typedef struct {
int id;
char name[50];
} Student;
Student students[] = {
{1, "Alice"},
{2, "Bob"},
{3, "Charlie"},
{4, "David"}
};
int n = sizeof(students) / sizeof(students[0]); // 计算数组长度
void swap(Student *a, Student *b) {
Student temp = *a;
*a = *b;
*b = temp;
}
for (int i = 0; i < n / 2; i++) {
swap(&students[i], &students[n - 1 - i]);
}
for (int i = 0; i < n; i++) {
printf("ID: %d, Name: %s\n", students[i].id, students[i].name);
}
完整代码示例:
#include<stdio.h>
typedef struct {
int id;
char name[50];
} Student;
void swap(Student *a, Student *b) {
Student temp = *a;
*a = *b;
*b = temp;
}
int main() {
Student students[] = {
{1, "Alice"},
{2, "Bob"},
{3, "Charlie"},
{4, "David"}
};
int n = sizeof(students) / sizeof(students[0]);
for (int i = 0; i < n / 2; i++) {
swap(&students[i], &students[n - 1 - i]);
}
for (int i = 0; i < n; i++) {
printf("ID: %d, Name: %s\n", students[i].id, students[i].name);
}
return 0;
}
运行此代码将输出逆序排序后的结构体数组。