First, your code is C++ and not C, so I'll respond accordingly.
You can return a C++-style std::array
, which is an object rather than a C-style array and thus can be returned by value:
#include <iostream>
#include <array>
int v[10] = { 1,2,3,44,55,66,77,8,9,1 };
auto fun()->std::array<int, 10>
{
std::array<int, 10> v;
v[0] = 5;
v[1] = 32;
//int v[10] = { 1,2,3,44,55,66,77,8,9,1 };/
return v;
}
int main()
{
auto v = fun();
for(size_t i = 0; i < 10; i++) {
std::cout << v[i] << std::endl;
}
}
You could have dynamically allocated the array instead, in which case you return a pointer and the caller is responsible for freeing it:
auto fun2()->int*
{
auto v = new int[10];
v[0] = 1;
// assign other elements
return v;
}
int main()
{
auto t2 = fun2();
for (int i = 0; i < 10; i++)
std::cout << t2[i] << std::endl;
delete[] t2;
}
You're simply not allowed to allocate the array on the stack and then return it, because the lifetime of stack variables is over as soon as your function returns. With that said, this example is valid because the array is allocated in main
's stack frame and outlives all of its uses:
void fillIn(int* ar, size_t len) {
for (size_t i = 0; i < len; i++) {
ar[i] = 32; // or whatever logic you want
}
}
int main()
{
int x[10];
fillIn(x, 10);
for (int i = 0; i < 10; i++) {
std::cout << x[i] << std::endl;
}
}