MST
星途 面试题库

面试题:C语言结构体数组的内存管理与复杂操作

设计一个结构体表示员工信息struct Employee { char name[30]; int id; struct { char department[30]; float salary; } details; }; 动态分配内存创建一个可容纳100个员工信息的结构体数组,从文件中读取员工信息填充该数组(假设文件格式为每行一个员工信息,格式为:名字 编号 部门 薪资)。完成后,释放分配的内存。同时,编写一个函数,能够根据员工编号对这个结构体数组进行快速排序(使用快速排序算法),并在主函数中调用此函数进行排序并输出排序后的员工信息。
41.6万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

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

// 定义员工结构体
struct Employee {
    char name[30];
    int id;
    struct {
        char department[30];
        float salary;
    } details;
};

// 交换两个员工信息
void swap(struct Employee *a, struct Employee *b) {
    struct Employee temp = *a;
    *a = *b;
    *b = temp;
}

// 快速排序分区函数
int partition(struct Employee arr[], int low, int high) {
    int pivot = arr[high].id;
    int i = (low - 1);

    for (int j = low; j <= high - 1; j++) {
        if (arr[j].id < pivot) {
            i++;
            swap(&arr[i], &arr[j]);
        }
    }
    swap(&arr[i + 1], &arr[high]);
    return (i + 1);
}

// 快速排序函数
void quickSort(struct Employee arr[], int low, int high) {
    if (low < high) {
        int pi = partition(arr, low, high);

        quickSort(arr, low, pi - 1);
        quickSort(arr, pi + 1, high);
    }
}

int main() {
    struct Employee *employees = (struct Employee *)malloc(100 * sizeof(struct Employee));
    if (employees == NULL) {
        printf("内存分配失败\n");
        return 1;
    }

    FILE *file = fopen("employees.txt", "r");
    if (file == NULL) {
        printf("文件打开失败\n");
        free(employees);
        return 1;
    }

    int count = 0;
    while (fscanf(file, "%29s %d %29s %f", employees[count].name, &employees[count].id, employees[count].details.department, &employees[count].details.salary) != EOF && count < 100) {
        count++;
    }

    fclose(file);

    quickSort(employees, 0, count - 1);

    // 输出排序后的员工信息
    for (int i = 0; i < count; i++) {
        printf("Name: %s, ID: %d, Department: %s, Salary: %.2f\n", employees[i].name, employees[i].id, employees[i].details.department, employees[i].details.salary);
    }

    free(employees);

    return 0;
}
  1. 结构体定义:定义了struct Employee结构体来表示员工信息,包含姓名、编号、部门和薪资信息。
  2. 内存分配:使用malloc动态分配内存,创建可容纳100个员工信息的结构体数组。
  3. 文件读取:从文件中读取员工信息,填充到结构体数组中。
  4. 快速排序:实现了快速排序算法,根据员工编号对结构体数组进行排序。
  5. 输出排序结果:在主函数中调用快速排序函数,并输出排序后的员工信息。
  6. 内存释放:使用free释放动态分配的内存。