Reputation: 44568
struct MyStruct
{
int i;
double arr[10];
};
struct MyStruct func()
{
};
When returned from the function, will be fully copied to a local variable?
struct Mystruct ms = func();
Upvotes: 1
Views: 477
Reputation: 213513
The correct way to do this:
void func(struct MyStruct* by_ref);
int main()
{
struct MyStruct ms;
func(&ms);
}
This won't upload a bombastic struct on the stack, nor will you get issues with static variables. Returning a pointer to a static variable is very bad for the following reasons:
static uint8 static_str[6]; uint8* func(const uint8 str[6]) { uint8 i; for(i=0; i<6; i++) { static_str[i] = str[i]; } return static_str; } int main() { print_strings(func(“hello”), func(“world”)); }
The output from a function printing the two strings will be either “hello hello” or “world world” (depending on the order of evaluation of function parameters).
Upvotes: 0
Reputation: 1114
You have no return value so in any case you need to set that. Furthermore, it is better to use a pointer:
struct MyStruct* func()
{
struct MyStruct *pMyStruct=calloc(1,sizeof(struct MyStruct));
/* fill struct */
return pMyStruct;
};
Upvotes: -1