面试题答案
一键面试#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
struct book {
char title[50];
float price;
};
struct book* createBookArray(int n) {
struct book* books = (struct book*)malloc(n * sizeof(struct book));
if (books == NULL) {
return NULL;
}
srand(time(NULL));
for (int i = 0; i < n; i++) {
snprintf(books[i].title, sizeof(books[i].title), "Book%d", i + 1);
books[i].price = (float)(rand() % 1000) / 10.0;
}
return books;
}
void freeBookArray(struct book* books) {
free(books);
}
要释放动态分配的内存,可调用 freeBookArray
函数,传入指向该结构体数组的指针,如下:
int main() {
int n = 5;
struct book* myBooks = createBookArray(n);
if (myBooks != NULL) {
// 使用数组
for (int i = 0; i < n; i++) {
printf("Title: %s, Price: %.2f\n", myBooks[i].title, myBooks[i].price);
}
freeBookArray(myBooks);
}
return 0;
}
- 动态内存分配:使用
malloc
函数为包含n
个struct book
元素的数组分配内存。如果分配失败,返回NULL
。 - 初始化:利用
snprintf
生成随机书名,使用rand
生成随机价格。 - 内存释放:定义
freeBookArray
函数,使用free
释放之前分配的内存,避免内存泄漏。在main
函数中使用完数组后调用该函数释放内存。