MST

星途 面试题库

面试题:C语言结构体嵌套中的指针引用

定义一个结构体嵌套的多层结构,struct Level1 { struct Level2 *ptr; }; struct Level2 { struct Level3 *ptr; }; struct Level3 { int data; }; 编写代码实现创建这样一个多层嵌套的结构体实例,并正确初始化各级指针,同时给出访问最内层data成员的完整代码,并解释在这个过程中可能出现的空指针风险及如何避免。
27.4万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

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

// 定义结构体
struct Level3 {
    int data;
};

struct Level2 {
    struct Level3 *ptr;
};

struct Level1 {
    struct Level2 *ptr;
};

int main() {
    // 创建结构体实例并初始化各级指针
    struct Level1 *level1 = (struct Level1 *)malloc(sizeof(struct Level1));
    if (level1 == NULL) {
        perror("malloc for Level1");
        return 1;
    }

    struct Level2 *level2 = (struct Level2 *)malloc(sizeof(struct Level2));
    if (level2 == NULL) {
        perror("malloc for Level2");
        free(level1);
        return 1;
    }

    struct Level3 *level3 = (struct Level3 *)malloc(sizeof(struct Level3));
    if (level3 == NULL) {
        perror("malloc for Level3");
        free(level2);
        free(level1);
        return 1;
    }

    level1->ptr = level2;
    level2->ptr = level3;
    level3->data = 42;

    // 访问最内层data成员
    if (level1 != NULL && level1->ptr != NULL && level1->ptr->ptr != NULL) {
        printf("The value of data is: %d\n", level1->ptr->ptr->data);
    } else {
        printf("There is a null pointer, cannot access data.\n");
    }

    // 释放内存
    free(level3);
    free(level2);
    free(level1);

    return 0;
}

空指针风险及避免方法

  1. 风险:在创建结构体实例时,如果malloc分配内存失败,会返回空指针。例如,在mallocLevel1Level2Level3分配内存失败时,如果没有进行空指针检查,后续对指针的解引用操作(如level1->ptr)就会导致未定义行为,程序可能崩溃。
  2. 避免方法:每次使用malloc分配内存后,立即检查返回值是否为NULL。如上述代码中,在每次malloc后都进行了空指针检查,如果分配失败,及时释放之前已分配的内存,并给出错误提示,避免后续的空指针引用问题。在访问最内层data成员时,也要先检查各级指针是否为NULL,确保指针有效后再进行解引用操作。