Returning a struct containing array in C

100 views Asked by At

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?

2

There are 2 answers

0
gulpr On BEST ANSWER

Can I return a struct that contains an array from a function or is it undefined behaviour?

As structs and unions 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.

2
pts On

Yes, the array gets copied just like any other struct member, as if it was char arr0, arr1, ..., arr99; in the struct.

This is true since C89 (ANSI C), the first C standard.