阅读量:0
在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; }
运行此代码将输出逆序排序后的结构体数组。