MST

星途 面试题库

面试题:C语言结构体在函数参数传递中的性能对比 - 中等难度

在C语言中,有一个结构体定义如下:struct Point { int x; int y; }; 请分别写出通过值传递和指针传递该结构体到一个函数,函数功能是计算该点到原点(0, 0)的距离,并说明这两种传递方式在性能上有何不同。
31.4万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试

值传递

#include <stdio.h>
#include <math.h>

struct Point {
    int x;
    int y;
};

// 函数声明
double distanceByValue(struct Point p);

int main() {
    struct Point p = {3, 4};
    double dist = distanceByValue(p);
    printf("通过值传递计算的距离: %lf\n", dist);
    return 0;
}

// 函数定义
double distanceByValue(struct Point p) {
    return sqrt(p.x * p.x + p.y * p.y);
}

指针传递

#include <stdio.h>
#include <math.h>

struct Point {
    int x;
    int y;
};

// 函数声明
double distanceByPointer(struct Point *p);

int main() {
    struct Point p = {3, 4};
    double dist = distanceByPointer(&p);
    printf("通过指针传递计算的距离: %lf\n", dist);
    return 0;
}

// 函数定义
double distanceByPointer(struct Point *p) {
    return sqrt(p->x * p->x + p->y * p->y);
}

性能差异

  • 值传递:在值传递时,函数会复制整个结构体的内容到函数栈中。如果结构体较大,复制操作会消耗较多的时间和空间,性能较低。
  • 指针传递:指针传递时,函数仅复制结构体的地址(通常为4字节或8字节,取决于系统架构),相比于复制整个结构体,消耗的时间和空间都较少,在处理大结构体时性能更高。