Home >Backend Development >C++ >How to Return an Array from a Function in C without Losing Data?
Returning Arrays from a Function in C
When returning an array from a function in C , it's essential to understand the intricacies of memory management. By default, local arrays allocated on the stack within the function are destroyed when the function exits. This behavior leads to undefined behavior if attempts are made to access these arrays outside the function.
In the provided code, an array c is created on the stack within the uni function:
<code class="c++">int c[10];</code>
Although this array is successfully populated with values in the function, the values are lost once the function returns and the array is destroyed. This results in the unexpected output you encounter.
To overcome this issue, you can adopt two alternative approaches:
Using a Pointer:
Modify the uni function to return a pointer to the allocated array:
<code class="c++">int* uni(int *a,int *b) { int* c = new int[10]; // Allocate array on heap int i = 0; // ...same code as before... return c; }</code>
In main, you should be responsible for deallocating the memory allocated in the heap:
<code class="c++">int main() { // ...same code as before... delete[] c; // Deallocate array from heap // ... }</code>
Using a Struct:
Another approach involves wrapping the array within a struct and returning the struct:
<code class="c++">struct myArray { int array[10]; }; myArray uni(int *a,int *b) { myArray c; int i = 0; // ...same code as before... return c; }</code>
In this case, the struct is returned by value, ensuring a copy of the array is created in the main function. Struct return values can be efficiently copied due to the value semantics of structs.
The above is the detailed content of How to Return an Array from a Function in C without Losing Data?. For more information, please follow other related articles on the PHP Chinese website!