MST

星途 面试题库

面试题:C语言动态分配结构体数组内存后复杂数据成员初始化

定义一个结构体struct Book { char title[50]; float price; int pages; struct Author { char name[30]; int age; } author; }; 编写代码动态分配一个包含3个Book结构体元素的数组内存,对每个元素的title、price、pages以及author的name和age进行合理初始化,最后释放内存。
34.3万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

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

// 定义结构体
struct Book {
    char title[50];
    float price;
    int pages;
    struct Author {
        char name[30];
        int age;
    } author;
};

int main() {
    // 动态分配包含3个Book结构体元素的数组内存
    struct Book *books = (struct Book *)malloc(3 * sizeof(struct Book));

    if (books == NULL) {
        printf("内存分配失败\n");
        return 1;
    }

    // 初始化每个元素
    for (int i = 0; i < 3; i++) {
        // 合理初始化title
        snprintf(books[i].title, sizeof(books[i].title), "Book %d", i + 1);
        // 合理初始化price
        books[i].price = (float)(i + 1) * 10.0f;
        // 合理初始化pages
        books[i].pages = (i + 1) * 100;
        // 合理初始化author的name
        snprintf(books[i].author.name, sizeof(books[i].author.name), "Author %d", i + 1);
        // 合理初始化author的age
        books[i].author.age = 25 + i;
    }

    // 打印初始化后的数据
    for (int i = 0; i < 3; i++) {
        printf("Title: %s\n", books[i].title);
        printf("Price: %.2f\n", books[i].price);
        printf("Pages: %d\n", books[i].pages);
        printf("Author Name: %s\n", books[i].author.name);
        printf("Author Age: %d\n\n", books[i].author.age);
    }

    // 释放内存
    free(books);

    return 0;
}