在ac函数中返回struct

Lea*_*ppi 2 c struct pointers

我有类似下面的C代码:

struct MyStruct MyFunction (something here)
{
    struct MyStruct data;

    //Some code here

    return data;
}
Run Code Online (Sandbox Code Playgroud)

返回值是数据存储块的引用还是副本?MyFunction应该返回struct MyStruct*(带有相应的内存分配)而不是struct MyStruct吗?

Oli*_*rth 6

在C中没有引用这样的东西.从语义上讲,你正在返回结构的副本.但是,编译器可以优化它.

您不能返回局部变量的地址,因为它在函数返回时超出范围.你可以返回你刚刚做过的东西的地址malloc,但是你需要明确某个人free在某个时候需要那个指针.