C语言中如何对结构体数组进行逆序排序

avatar
作者
筋斗云
阅读量:0

在C语言中,要对结构体数组进行逆序排序,你可以使用以下方法:

  1. 首先定义一个结构体类型,例如:
typedef struct {     int id;     char name[50]; } Student; 
  1. 创建一个结构体数组并填充数据:
Student students[] = {     {1, "Alice"},     {2, "Bob"},     {3, "Charlie"},     {4, "David"} }; int n = sizeof(students) / sizeof(students[0]); // 计算数组长度 
  1. 编写一个交换结构体元素的函数:
void swap(Student *a, Student *b) {     Student temp = *a;     *a = *b;     *b = temp; } 
  1. 使用循环逆序排序结构体数组:
for (int i = 0; i < n / 2; i++) {     swap(&students[i], &students[n - 1 - i]); } 
  1. 打印逆序排序后的结构体数组:
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; } 

运行此代码将输出逆序排序后的结构体数组。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!