面试题答案
一键面试#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义教师结构体
typedef struct Teacher {
char name[50];
int yearsOfTeaching;
} Teacher;
// 定义学生结构体
typedef struct Student {
char name[50];
int age;
float score;
} Student;
// 定义班级结构体
typedef struct Class {
Teacher *teacher;
Student *students;
int studentCount;
} Class;
// 创建班级的函数
Class* createClass(const char* teacherName, int teacherYears, const char** studentNames, int* studentAges, float* studentScores, int studentCount) {
if (teacherName == NULL || studentNames == NULL || studentAges == NULL || studentScores == NULL || studentCount <= 0) {
return NULL;
}
Class* newClass = (Class*)malloc(sizeof(Class));
if (newClass == NULL) {
return NULL;
}
newClass->teacher = (Teacher*)malloc(sizeof(Teacher));
if (newClass->teacher == NULL) {
free(newClass);
return NULL;
}
strcpy(newClass->teacher->name, teacherName);
newClass->teacher->yearsOfTeaching = teacherYears;
newClass->students = (Student*)malloc(studentCount * sizeof(Student));
if (newClass->students == NULL) {
free(newClass->teacher);
free(newClass);
return NULL;
}
for (int i = 0; i < studentCount; i++) {
strcpy(newClass->students[i].name, studentNames[i]);
newClass->students[i].age = studentAges[i];
newClass->students[i].score = studentScores[i];
}
newClass->studentCount = studentCount;
return newClass;
}
// 释放班级内存的函数
void freeClass(Class* class) {
if (class != NULL) {
if (class->teacher != NULL) {
free(class->teacher);
}
if (class->students != NULL) {
free(class->students);
}
free(class);
}
}
你可以使用以下方式调用这个函数:
int main() {
const char* teacherName = "Mr. Smith";
int teacherYears = 10;
const char* studentNames[] = {"Alice", "Bob", "Charlie"};
int studentAges[] = {18, 19, 20};
float studentScores[] = {85.5, 90.0, 78.0};
int studentCount = 3;
Class* myClass = createClass(teacherName, teacherYears, studentNames, studentAges, studentScores, studentCount);
if (myClass != NULL) {
// 使用班级数据
printf("Teacher: %s, Years of Teaching: %d\n", myClass->teacher->name, myClass->teacher->yearsOfTeaching);
for (int i = 0; i < myClass->studentCount; i++) {
printf("Student %d: %s, Age: %d, Score: %.2f\n", i + 1, myClass->students[i].name, myClass->students[i].age, myClass->students[i].score);
}
freeClass(myClass);
} else {
printf("Failed to create class.\n");
}
return 0;
}
代码说明:
- 结构体定义:分别定义了
Teacher
、Student
和Class
结构体,Class
结构体中包含Teacher
指针和Student
数组指针。 createClass
函数:- 进行输入参数的有效性检查,如果输入参数有
NULL
或者学生数量小于等于0,返回NULL
。 - 为
Class
结构体分配内存,如果分配失败返回NULL
。 - 为
Teacher
结构体分配内存,如果分配失败,释放Class
结构体并返回NULL
。 - 为
Student
数组分配内存,如果分配失败,释放Teacher
结构体和Class
结构体并返回NULL
。 - 填充教师和学生的数据。
- 返回创建好的
Class
结构体指针。
- 进行输入参数的有效性检查,如果输入参数有
freeClass
函数:- 释放
Class
结构体中teacher
和students
分配的内存,最后释放Class
结构体本身。
- 释放
main
函数:- 调用
createClass
函数创建班级并检查是否创建成功。 - 如果创建成功,输出班级信息。
- 调用
freeClass
函数释放班级内存。
- 调用