C++ return array | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 12

C++ return array

what's wrong with this code ? #include <iostream> int *getArray() { int b[] = { 4, 1, 2, 3 }; return b; } int main() { int *a = getArray(); std::cout << a[0] << std::endl; return 0; }

17th Mar 2019, 2:31 PM
NoxFly
NoxFly - avatar
5 Answers
+ 16
The scope of your array created in the function is local. When you return the array from the function, you are returning a pointer to the array local to getArray(). Accessing the pointer content in main() may cause a segfault, as the content has expired. To make things work, you need to allocate dynamic memory using "new". #include <iostream> int *getArray() { int* b = new int[5]{ 4, 1, 2, 3 }; return b; } int main() { int *a = getArray(); std::cout << a[0] << std::endl; delete a; return 0; }
17th Mar 2019, 2:38 PM
Fermi
Fermi - avatar
+ 7
To add to Fermi 's excellent answer To return an array, you'll have either to return the result of an allocation or use some some tricks like the structure mapping It is also usable in C. struct retArray5{ int arr[5]; }; retArray5 getArray(){ // ... } int main(){ int * a = getArray().arr; // do not return a if not in main //... } Edit: corrected thanks to ~ swim ~ statement, I wrote it without checking it, my bad
17th Mar 2019, 5:09 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 5
Thanks
17th Mar 2019, 3:01 PM
NoxFly
NoxFly - avatar
+ 1
Fermi good but how new can provide global scope to array ?
17th Mar 2019, 3:46 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Hi
19th Mar 2019, 1:18 PM
Rima Ferrahi