vehomzzz
vehomzzz

Reputation: 44568

Return a struct from a function containg a static array in C

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

Answers (4)

Lundin
Lundin

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:

  1. It breaks private encaptulation. Very bad program design.
  2. A multi-threaded program doing this gets vulnerable.
  3. Pure bugs, as in this example:
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

Martin
Martin

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

BlackBear
BlackBear

Reputation: 22979

Yes, if func() returns a variable of type Mystruct.

Upvotes: 0

vz0
vz0

Reputation: 32923

Yes you can, the structure will be fully copied.

Upvotes: 5

Related Questions