从C中的函数返回`struct`

今天,我在教学上几个朋友如何用C struct秒。其中一个询问您是否可以struct从函数中返回a ,我回答:“不!您将返回指向动态malloced struct的指针。”


来自主要从事C ++工作的人,我期望无法struct通过值返回s。在C ++中,您可以operator =为您的对象重载,并且完全有意义的是有一个函数可以按值返回您的对象。但是,在C语言中,您没有该选项,因此让我开始思考编译器的实际作用。考虑以下:


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;吗?可能要问的问题是:return与=签字共同声明的语句到底做了什么?


[edit]:好的,我只是指出这struct b = a是一个语法错误-没错,我是个白痴!但这使事情变得更加复杂!使用struct MyObj b = a确实有效!我在这里想念什么?


德玛西亚99
浏览 693回答 3
3回答

Helenr

您可以从函数返回结构(或使用=运算符),而不会出现任何问题。这是语言中定义明确的部分。唯一的问题struct b = a是您没有提供完整的类型。&nbsp; struct MyObj b = a会很好。您也可以将结构传递给函数-为了传递参数,返回值和分配,结构与任何内置类型完全相同。这是一个简单的演示程序,可完成所有这三个操作-将结构作为参数传递,从函数返回结构,并在赋值语句中使用结构:#include <stdio.h>struct a {&nbsp; &nbsp;int i;};struct a f(struct a x){&nbsp; &nbsp;struct a r = x;&nbsp; &nbsp;return r;}int main(void){&nbsp; &nbsp;struct a x = { 12 };&nbsp; &nbsp;struct a y = f(x);&nbsp; &nbsp;printf("%d\n", y.i);&nbsp; &nbsp;return 0;}下一个示例几乎完全相同,但是使用内置int类型进行演示。对于参数传递,赋值等的值传递,这两个程序具有相同的行为:#include <stdio.h>int f(int x)&nbsp;{&nbsp; int r = x;&nbsp; return r;}int main(void){&nbsp; int x = 12;&nbsp; int y = f(x);&nbsp; printf("%d\n", y);&nbsp; return 0;}

慕勒3428872

进行诸如之类的调用时a = foo();,编译器可能会将结果结构的地址压入堆栈,并将其作为“隐藏”指针传递给foo()函数。实际上,它可能变为:void foo(MyObj *r) {&nbsp; &nbsp; struct MyObj a;&nbsp; &nbsp; // ...&nbsp; &nbsp; *r = a;}foo(&a);但是,此操作的确切实现取决于编译器和/或平台。正如Carl Norum所指出的,如果结构足够小,它甚至可能会完全传回寄存器中。
打开App,查看更多内容
随时随地看视频慕课网APP