#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;
}