1

Here is a structure:

struct elem {
    int a[100];
    int val;
};

elem foo() {
    elem Result;
    Result.a[0] = 5;
    return Result;
}

int main () {
    elem aux = foo();
    //is Result passed back to aux, so that we can use its array?
    cout<<aux.a[0]<<"\n"; // 5
}

I know that functions ca return simple structures. Can they also return structures that contain arrays? What happens within the memory?

And also: when we declare elem Result; in the function, is the array initialised with 0, or it just takes random values?

Andrei Margeloiu
  • 849
  • 2
  • 12
  • 17
  • 1
    Yes We Can!!!!! – barak manos Feb 04 '17 at 21:23
  • If you _want_ it to be initialized to zero, `elem Result = {0};` is a very concise way to do so. See https://stackoverflow.com/questions/201101/how-to-initialize-all-members-of-an-array-to-the-same-value/9812815 – odougs Apr 12 '19 at 04:25

1 Answers1

4

Yes you can, in both C and C++.

The array is copied element-by-element along with the rest of the struct. This might be slow for large arrays.


is the array initialised with 0, or it just takes random values?

The array is not initialized, so it contains indeterminate values. Accessing them causes undefined behavior.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
  • Why aren't the arrays returned in the same way (copied when returned)? – Andrei Margeloiu Feb 04 '17 at 21:22
  • 2
    ¯\\_(ツ)_/¯ probably because it's slow for large arrays and so the C standard wants to discourage it. – Emil Laine Feb 04 '17 at 21:23
  • 1
    @AndreiMargeloiu; Because array have special feature that when they used in an expression they converted to pointer to its first element, with some exception. Arrays can't return from a function. – haccks Feb 04 '17 at 21:24
  • 1
    So, if we want a function to return an array, can we 'pack' the array in a struct ? – Andrei Margeloiu Feb 04 '17 at 21:34
  • @AndreiMargeloiu Yes. Usually in C you declare the array outside the function and pass a pointer to the array into the function to fill it. – Emil Laine Feb 04 '17 at 21:35
  • 1
    If an array is not initialised, accessing its elements gives undefined behaviour. Containing "random values" is only one possible manifestation of that. – Peter Feb 04 '17 at 22:36