MST

星途 面试题库

面试题:C语言结构体指针高级难度题

给定一个结构体数组struct book { char title[50]; char author[30]; int pages; } books[10]; 请使用结构体指针实现对该数组按页数(pages)进行升序排序,并给出详细的实现思路和代码。
12.4万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 定义一个比较函数,用于比较两个结构体指针指向的结构体中 pages 成员的大小。
  2. 使用 qsort 函数,它是C标准库提供的快速排序函数,通过传入比较函数,实现对结构体数组按 pages 成员升序排序。

代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 定义结构体
struct book {
    char title[50];
    char author[30];
    int pages;
};

// 比较函数,用于qsort
int compare(const void *a, const void *b) {
    struct book *book1 = (struct book *)a;
    struct book *book2 = (struct book *)b;
    return (book1->pages - book2->pages);
}

int main() {
    struct book books[10] = {
        {"Book1", "Author1", 200},
        {"Book2", "Author2", 150},
        {"Book3", "Author3", 250},
        {"Book4", "Author4", 180},
        {"Book5", "Author5", 300},
        {"Book6", "Author6", 120},
        {"Book7", "Author7", 220},
        {"Book8", "Author8", 160},
        {"Book9", "Author9", 280},
        {"Book10", "Author10", 140}
    };

    // 使用qsort进行排序
    qsort(books, 10, sizeof(struct book), compare);

    // 输出排序后的结果
    for (int i = 0; i < 10; i++) {
        printf("Title: %s, Author: %s, Pages: %d\n", books[i].title, books[i].author, books[i].pages);
    }

    return 0;
}