Can anybody help me fixing this code, I am tryin to return an array from a c++ function. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Can anybody help me fixing this code, I am tryin to return an array from a c++ function.

https://code.sololearn.com/cSV54acRpZuL/?ref=app

23rd Dec 2020, 8:44 PM
Saeed Alqassabi
Saeed Alqassabi - avatar
7 Answers
+ 4
In the getData function make data static so that it remains when out of scope. Once it is out of scope it is destroyed which is where your problem lies. static int data[] = {1, 0};
23rd Dec 2020, 9:01 PM
ChaoticDawg
ChaoticDawg - avatar
+ 2
So ChaoticDawg the problem was because I was sending an address of a destroyed variable, am I right?.
24th Dec 2020, 1:36 AM
Saeed Alqassabi
Saeed Alqassabi - avatar
+ 2
Saeed Alqassabi Pretty much
24th Dec 2020, 1:37 AM
ChaoticDawg
ChaoticDawg - avatar
+ 2
Thanks ChaoticDawg and rodwynnejones for the help, I appreciate it.
24th Dec 2020, 1:38 AM
Saeed Alqassabi
Saeed Alqassabi - avatar
23rd Dec 2020, 9:03 PM
rodwynnejones
rodwynnejones - avatar
+ 1
You are trying to access "data" variable (which is declared inside getData() function's scope) in std::cout. Don't mix static with scoping. Static means that variable will remain the same until the program termination, but cannot be accessed out of the scope of your getData() function. Solution will be if you replace data[0] and data[1] inside your main() (line 14.) with data2[0] and [1] because getData()'s array return value is stored inside data2 which is declared inside your main()'s scope where you're accessing from.
24th Dec 2020, 11:31 PM
Baltazarus
Baltazarus - avatar
0
Thanks *Nitrocell, it is 100% clear.
25th Dec 2020, 6:26 AM
Saeed Alqassabi
Saeed Alqassabi - avatar