今天我正在教几个朋友如何使用 C structs。其中一个人问你是否可以struct从函数中返回 a,我回答说:“不!你应该返回指向动态mallocedstruct的指针。”
struct
malloc
来自主要从事 C 的人,我期望无法struct按值返回 s。在 C 中,您可以operator =为您的对象重载 ,并且拥有一个按值返回对象的函数是完全有意义的。但是,在 C 语言中,您没有该选项,因此我开始思考编译器实际上在做什么。考虑以下:
operator =
struct MyObj{ double x, y; }; struct MyObj foo(){ struct MyObj a; a.x = 10; a.y = 10; return a; } int main () { struct MyObj a; a = foo(); // This DOES work struct b = a; // This does not work return 0; }
我理解为什么struct b = a;不应该工作——你不能operator =为你的数据类型重载。它是如何a = foo();编译好的?它是否意味着其他东西struct b = a;?也许要问的问题是:与signreturn连用的语句到底是做什么的?=
struct b = a;
a = foo();
return
=
=您可以毫无问题地从函数(或使用运算符)返回结构。它是语言中定义明确的部分。唯一的问题struct b = a是您没有提供完整的类型。 struct MyObj b = a会工作得很好。您也可以将结构传递 给 函数 - 用于参数传递、返回值和赋值的结构与任何内置类型完全相同。
struct b = a
struct MyObj b = a
这是一个简单的演示程序,它完成了所有三个操作 - 将结构作为参数传递,从函数返回结构,并在赋值语句中使用结构:
#include <stdio.h> struct a { int i; }; struct a f(struct a x) { struct a r = x; return r; } int main(void) { struct a x = { 12 }; struct a y = f(x); printf("%d\n", y.i); return 0; }
下一个示例几乎完全相同,但使用内置int类型进行演示。这两个程序在参数传递、赋值等的按值传递方面具有相同的行为:
int
#include <stdio.h> int f(int x) { int r = x; return r; } int main(void) { int x = 12; int y = f(x); printf("%d\n", y); return 0; }