+ 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; }
7 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;
}
+ 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
+ 5
Thanks
+ 1
Fermi good but how new can provide global scope to array ?
0
Hi