MST
星途 面试题库

面试题:C语言复杂结构体指针空指针判断及错误处理

有一个复杂的结构体嵌套定义如下:struct Inner { int value; }; struct Outer { struct Inner *innerPtr; struct Outer *next; }; 编写一个函数,该函数接收一个指向struct Outer的指针,在函数中对所有可能出现的空指针情况(包括innerPtr和next指针)进行判断和处理。对于innerPtr为空的情况,动态分配内存并初始化其value为 - 1;对于next为空的情况,打印'下一个Outer节点为空'。同时,要考虑内存释放和异常处理,防止内存泄漏。
40.9万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

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

struct Inner {
    int value;
};

struct Outer {
    struct Inner *innerPtr;
    struct Outer *next;
};

void processOuter(struct Outer *outer) {
    if (outer == NULL) {
        return;
    }

    struct Outer *current = outer;
    struct Outer *prev = NULL;

    while (current != NULL) {
        if (current->innerPtr == NULL) {
            current->innerPtr = (struct Inner *)malloc(sizeof(struct Inner));
            if (current->innerPtr == NULL) {
                // 内存分配失败,处理异常
                fprintf(stderr, "内存分配失败\n");
                // 释放之前分配的内存
                while (prev != NULL) {
                    struct Outer *temp = prev;
                    prev = prev->next;
                    if (temp->innerPtr != NULL) {
                        free(temp->innerPtr);
                    }
                    free(temp);
                }
                return;
            }
            current->innerPtr->value = -1;
        }

        if (current->next == NULL) {
            printf("下一个Outer节点为空\n");
        }

        prev = current;
        current = current->next;
    }

    // 释放所有分配的内存
    current = outer;
    while (current != NULL) {
        struct Outer *temp = current;
        current = current->next;
        if (temp->innerPtr != NULL) {
            free(temp->innerPtr);
        }
        free(temp);
    }
}