MST

星途 面试题库

面试题:C语言结构体嵌套在函数参数传递中的应用

给定如下结构体定义: ```c struct Point { int x; int y; }; struct Rectangle { struct Point topLeft; struct Point bottomRight; }; ``` 编写一个函数`calculateArea`,该函数接受一个`Rectangle`结构体指针作为参数,计算并返回该矩形的面积。同时编写主函数,创建一个`Rectangle`结构体变量并初始化,调用`calculateArea`函数并输出结果。
39.2万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#include <stdio.h>

struct Point {
    int x;
    int y;
};

struct Rectangle {
    struct Point topLeft;
    struct Point bottomRight;
};

// 计算矩形面积的函数
int calculateArea(struct Rectangle *rect) {
    int width = rect->bottomRight.x - rect->topLeft.x;
    int height = rect->bottomRight.y - rect->topLeft.y;
    return width * height;
}

int main() {
    struct Rectangle rect = {
       .topLeft = {1, 1},
       .bottomRight = {5, 5}
    };

    int area = calculateArea(&rect);
    printf("矩形的面积为: %d\n", area);

    return 0;
}