简体   繁体   中英

Returning struct in a c function

I have something like the folowing C code:

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

    //Some code here

    return data;
}

would the returning value be a reference or a copy of the memory block for data? Should MyFunction return struct MyStruct* (with the corresponding memory allocation) instead of struct MyStruct?

There is no such thing as a reference in C. So semantically speaking, you are returning a copy of the struct. However, the compiler may optimise this.

You cannot return the address of a local variable, as it goes out of scope when the function returns. You could return the address of something that you've just malloc -ed, but you'll need to make it clear that someone will need to free that pointer at some point.

It would return a copy. C is a pass-by-value language. Unless you specify that you are passing pointers around, structures get copied for assignments, return statements, and when used as function parameters.

It is returned as copy. BTW, you should not return it's reference because it has automatic storage duration ( ie, data resides on stack ).

I have had problems with this (a function in a DLL returning a struct) and have investigated it. Returning a struct from a DLL to be used by people who might have a different compiler is not good practice, because of the following.

How this works depends on the implementation. Some implementations return small records in registers, but most get an invisible extra argument that points to a result struct in the local frame of the caller. On return, the pointer is used to copy data to the struct in the local frame of the caller. How this pointer is passed depends on the implementation again: as last argument, as first argument or as register.

As others said, returning references is not a good idea, as the struct you return might be in your local frame. I prefer functions that do not return such structs at all, but take a pointer to one and fill it up from inside the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM