MST

星途 面试题库

面试题:C语言结构体成员访问与操作(专家难度)

考虑一个复杂的结构体嵌套场景,有如下结构体定义: ```c struct point { int x; int y; }; struct rectangle { struct point top_left; struct point bottom_right; }; struct shape { char type[10]; union { struct point center; struct rectangle rect; } u; }; ``` 编写一个函数,该函数接收一个`struct shape`类型的指针数组和数组长度作为参数,对于所有类型为“rectangle”的形状,计算其面积并输出;对于类型为“point”的形状,输出其坐标。要求高效地使用指针偏移来访问结构体和联合体成员,并且代码要具有良好的可移植性。
18.6万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

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

void processShapes(struct shape *shapes[], int length) {
    for (int i = 0; i < length; i++) {
        if (strcmp(shapes[i]->type, "rectangle") == 0) {
            struct rectangle *rect = &shapes[i]->u.rect;
            int width = rect->bottom_right.x - rect->top_left.x;
            int height = rect->bottom_right.y - rect->top_left.y;
            printf("Rectangle area: %d\n", width * height);
        } else if (strcmp(shapes[i]->type, "point") == 0) {
            struct point *pt = &shapes[i]->u.center;
            printf("Point coordinates: (%d, %d)\n", pt->x, pt->y);
        }
    }
}