MST

星途 面试题库

面试题:C语言结构体数组在函数间传递

定义一个结构体struct Book { char title[50]; char author[30]; int pages; }; 编写一个函数,该函数接收一个结构体数组和数组的大小作为参数,功能是找到页数最多的那本书,并返回该书的标题。在主函数中创建一个结构体数组并调用这个函数,输出页数最多的书的标题。
38.5万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#include <stdio.h>
#include <string.h>

struct Book {
    char title[50];
    char author[30];
    int pages;
};

const char* findMostPagesBook(struct Book books[], int size) {
    int maxIndex = 0;
    for (int i = 1; i < size; i++) {
        if (books[i].pages > books[maxIndex].pages) {
            maxIndex = i;
        }
    }
    return books[maxIndex].title;
}

int main() {
    struct Book library[] = {
        {"C Primer Plus", "Stephen Prata", 960},
        {"Effective C++", "Scott Meyers", 336},
        {"Clean Code", "Robert C. Martin", 464}
    };
    int size = sizeof(library) / sizeof(library[0]);
    const char* mostPagesBookTitle = findMostPagesBook(library, size);
    printf("页数最多的书的标题: %s\n", mostPagesBookTitle);
    return 0;
}
  1. 结构体定义:定义了struct Book结构体,包含title(书名)、author(作者)和pages(页数)成员。
  2. 函数findMostPagesBook:该函数接收struct Book类型的数组和数组大小作为参数,通过遍历数组找到页数最多的书,并返回该书的标题。
  3. main函数:创建了一个struct Book类型的数组library,调用findMostPagesBook函数找到页数最多的书的标题,并输出结果。