1、函数返回结构体
可以将 struct(结构体)作为函数的返回值。这是 C 语言支持的一种功能,适用于需要从函数中返回多个数据的情况。返回一个结构体时,会发生结构体的复制,特别是对于大的结构体,这可能会导致性能问题。现代编译器通常会优化这类操作,但仍需谨慎使用。
#include <stdio.h> // 定义一个结构体类型 struct Point { int x; int y; }; // 返回一个结构体 struct Point getPoint(int a, int b) { struct Point p; p.x = a; p.y = b; return p; // 直接返回结构体 } int main() { struct Point p1 = getPoint(10, 20); printf("Point: (%d, %d)\n", p1.x, p1.y); return 0; }
2、返回结构体指针
返回结构体的指针通常是通过动态分配内存的方式完成的。需要使用 malloc
或 calloc
来为结构体分配内存,并确保调用者负责释放这些内存。适用于大的结构体,避免了拷贝开销。可以返回更复杂的数据结构,避免内存浪费。
#include <stdio.h> #include <stdlib.h> struct Person { int age; char name[50]; }; // 返回结构体指针 struct Person* createPerson(int age, const char* name) { struct Person* p = (struct Person*)malloc(sizeof(struct Person)); // 动态分配内存 if (p != NULL) { p->age = age; snprintf(p->name, sizeof(p->name), "%s", name); } return p; // 返回结构体指针 } int main() { struct Person* person = createPerson(25, "John Doe"); if (person != NULL) { printf("Age: %d, Name: %s\n", person->age, person->name); free(person); // 释放内存 } return 0; }
3、简化代码
使用结构体返回多个值可以使代码更加清晰,避免了返回多个参数或者使用指针返回多个值的复杂性。
#include <stdio.h> struct Point { int x; int y; }; // 计算并返回点的坐标 struct Point calculatePoint(int x1, int y1, int x2, int y2) { struct Point result; result.x = x2 - x1; // 计算x坐标差值 result.y = y2 - y1; // 计算y坐标差值 return result; } int main() { struct Point p = calculatePoint(0, 0, 5, 5); printf("Point coordinates: (%d, %d)\n", p.x, p.y); return 0; }