#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct book {
char title[50];
float price;
};
int main() {
struct book *books;
int initial_size = 10;
int new_size;
// 使用malloc分配能容纳10个book结构体的内存空间
books = (struct book *)malloc(initial_size * sizeof(struct book));
if (books == NULL) {
printf("内存分配失败\n");
return 1;
}
// 假设初始化一些数据
for (int i = 0; i < initial_size; i++) {
snprintf(books[i].title, sizeof(books[i].title), "Book %d", i + 1);
books[i].price = (float)(i + 1) * 10.0;
}
// 获取用户输入的新数量
printf("请输入新的数量: ");
scanf("%d", &new_size);
// 使用realloc动态调整内存空间大小
struct book *new_books = (struct book *)realloc(books, new_size * sizeof(struct book));
if (new_books == NULL) {
printf("内存重新分配失败\n");
free(books);
return 1;
}
books = new_books;
// 输出调整后的内容(假设原有数据不丢失)
for (int i = 0; i < new_size; i++) {
printf("Title: %s, Price: %.2f\n", books[i].title, books[i].price);
}
// 释放内存
free(books);
return 0;
}