值传递
#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字节,取决于系统架构),相比于复制整个结构体,消耗的时间和空间都较少,在处理大结构体时性能更高。