在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;
}
運行此代碼將輸出逆序排序后的結構體數組。