MST

星途 面试题库

面试题:C语言结构体指针作为函数参数的内存管理与优化

假设有一个复杂的结构体 `Employee`,它包含 `name`(动态分配的字符指针)、`department`(动态分配的字符指针)、`salary`(浮点数)和 `next`(指向 `Employee` 结构体的指针,用于构建链表)。编写一个函数 `addEmployee`,该函数接收一个 `Employee**`(指向 `Employee` 结构体指针的指针,用于表示链表头指针)和新员工的信息作为参数,在函数内动态分配内存创建新的 `Employee` 结构体节点,并将其正确插入到链表头部,同时要处理好内存分配失败的情况。另外编写一个函数 `freeEmployeeList`,接收链表头指针,释放链表中所有节点的内存(包括 `name` 和 `department` 动态分配的内存)。在 `main` 函数中测试这两个函数。
29.2万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

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

// 定义Employee结构体
typedef struct Employee {
    char *name;
    char *department;
    float salary;
    struct Employee *next;
} Employee;

// 向链表头部添加新员工
Employee* addEmployee(Employee **head, const char *newName, const char *newDepartment, float newSalary) {
    // 分配新的Employee结构体节点内存
    Employee *newEmployee = (Employee*)malloc(sizeof(Employee));
    if (newEmployee == NULL) {
        fprintf(stderr, "内存分配失败\n");
        return NULL;
    }

    // 分配name和department的内存并复制内容
    newEmployee->name = (char*)malloc(strlen(newName) + 1);
    if (newEmployee->name == NULL) {
        fprintf(stderr, "内存分配失败\n");
        free(newEmployee);
        return NULL;
    }
    strcpy(newEmployee->name, newName);

    newEmployee->department = (char*)malloc(strlen(newDepartment) + 1);
    if (newEmployee->department == NULL) {
        fprintf(stderr, "内存分配失败\n");
        free(newEmployee->name);
        free(newEmployee);
        return NULL;
    }
    strcpy(newEmployee->department, newDepartment);

    newEmployee->salary = newSalary;
    newEmployee->next = *head;
    *head = newEmployee;
    return newEmployee;
}

// 释放链表中所有节点的内存
void freeEmployeeList(Employee *head) {
    Employee *current = head;
    Employee *next;

    while (current != NULL) {
        next = current->next;
        free(current->name);
        free(current->department);
        free(current);
        current = next;
    }
}

int main() {
    Employee *head = NULL;

    // 添加员工
    addEmployee(&head, "Alice", "HR", 5000.0);
    addEmployee(&head, "Bob", "Engineering", 6000.0);

    // 释放链表内存
    freeEmployeeList(head);

    return 0;
}