Can I return a struct that contains an array from a function or is it undefined beahvior?
Does it matter what standard I use?
For example:
#include <string.h>
typedef struct struct_t{
char arr[100];
int number;
} struct_t;
struct_t func(void)
{
struct_t s1 = {.number = 0};
memcpy(s1.arr, "Hello World", sizeof("Hello World"));
return s1;
}
int main(void)
{
struct_t s2 = func();
return 0;
}
Will it deep copy s1.arr to s2.arr?
if not, Will s2.arr try to point to the same location as s2.arr?
Maybe it creates a new array and only copies s1.number to s2.number?
Or is it just UB?
As
structs andunions are passed to and returned from the function by value, it is a defined behaviour. An array is the same struct member as any other type.Bear in mind that the whole structure or union will be returned and it can be a costly operation.