MST

星途 面试题库

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

编写一个函数,该函数接受一个嵌套结构体作为参数,结构体定义如下: ```c struct Point { int x; int y; }; struct Rectangle { struct Point topLeft; struct Point bottomRight; }; ``` 函数的功能是计算矩形的面积并返回。请说明在传递这个嵌套结构体参数时,可能会遇到哪些性能问题,如何优化?
28.9万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试

代码实现

#include <stdio.h>

struct Point {
    int x;
    int y;
};

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

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

性能问题

  1. 内存拷贝开销:在C语言中,当结构体作为函数参数传递时,会进行值传递,即整个结构体的内容会被拷贝到函数栈中。对于嵌套结构体struct Rectangle,包含两个struct Point,拷贝的内存量相对较大,尤其是结构体更大更复杂时,这种拷贝操作会带来明显的性能开销。
  2. 栈空间占用:大量的数据拷贝到栈上,可能会导致栈空间占用过多。如果函数调用层级较深,且频繁传递大结构体,可能导致栈溢出问题。

优化方法

  1. 传递指针:可以通过传递结构体指针来代替结构体值传递。这样只需要拷贝一个指针(通常为4字节或8字节,取决于系统架构),而不是整个结构体。
int calculateRectangleAreaByPointer(struct Rectangle *rect) {
    int width = rect->bottomRight.x - rect->topLeft.x;
    int height = rect->bottomRight.y - rect->topLeft.y;
    return width * height;
}
  1. 使用静态或全局变量:如果合适的话,可以将结构体定义为静态变量或全局变量,函数直接访问这些变量,避免参数传递带来的开销。但这种方法需要注意多线程环境下的线程安全问题。
static struct Rectangle globalRect;

int calculateRectangleAreaByGlobal() {
    int width = globalRect.bottomRight.x - globalRect.topLeft.x;
    int height = globalRect.bottomRight.y - globalRect.topLeft.y;
    return width * height;
}