Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to return a struct in C or C++?

What I understand is that this shouldn't be done, but I believe I've seen examples that do something like this (note code is not necessarily syntactically correct but the idea is there)

typedef struct{     int a,b; }mystruct; 

And then here's a function

mystruct func(int c, int d){     mystruct retval;     retval.a = c;     retval.b = d;     return retval; } 

I understood that we should always return a pointer to a malloc'ed struct if we want to do something like this, but I'm positive I've seen examples that do something like this. Is this correct? Personally I always either return a pointer to a malloc'ed struct or just do a pass by reference to the function and modify the values there. (Because my understanding is that once the scope of the function is over, whatever stack was used to allocate the structure can be overwritten).

Let's add a second part to the question: Does this vary by compiler? If it does, then what is the behavior for the latest versions of compilers for desktops: gcc, g++ and Visual Studio?

Thoughts on the matter?

like image 433
jzepeda Avatar asked Mar 06 '12 19:03

jzepeda


People also ask

Can I return struct in C?

Return struct from a function Here, the getInformation() function is called using s = getInformation(); statement. The function returns a structure of type struct student . The returned structure is displayed from the main() function. Notice that, the return type of getInformation() is also struct student .

Can structs be returned?

We learned above that we can “destructure” a struct and return it as a tuple. To return an array of structs, we will do the same thing. Each value in the returned tuple will represent a field in the struct.

Does C Copy structs?

In C/C++, we can assign a struct (or class in C++ only) variable to another variable of same type. When we assign a struct variable to another, all members of the variable are copied to the other struct variable.

Can you return an array of structs in C?

C programming does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.


1 Answers

It's perfectly safe, and it's not wrong to do so. Also: it does not vary by compiler.

Usually, when (like your example) your struct is not too big I would argue that this approach is even better than returning a malloc'ed structure (malloc is an expensive operation).

like image 119
Pablo Santa Cruz Avatar answered Sep 19 '22 05:09

Pablo Santa Cruz