0

Why i'm getting this weird output ? Maybe it's Initializing "w" on every member call ? also "w" address remains the same

struct window { int width; int height; }; window * create (int x,int y){ window w; w.width = x; w.height = y; return &w; } int main (){ window * win = create (800,600); cout<<win-> width <<endl; cout <<win -> height <<endl; } output: 800 1376882740

23rd Jun 2017, 11:58 PM
Mazin
Mazin - avatar
5 odpowiedzi
+ 9
The reason why the return value isn't correct is because your function returns the address of a local variable. In this case, 'w' is a local object of struct window - The memory allocated to store the local object is located on the stack, which gets deallocated when the function returns. As soon as you return from the function, 'w' goes out of place and same goes for the address of it. This causes garbage values to be assigned to some parts of your struct object in main().
24th Jun 2017, 4:00 AM
Hatsy Rei
Hatsy Rei - avatar
+ 1
thank you Nicolas but unfortunately it didn't work same weird output: 1 -1226127952
24th Jun 2017, 12:52 AM
Mazin
Mazin - avatar
+ 1
Solved it my fellow citzen. Hope it helps in your learning. There are multiple ways to do it. It's just one of them. https://code.sololearn.com/cBflJIvzPMFK/?ref=app
24th Jun 2017, 1:23 AM
Nicolas Cendron Fernandes
Nicolas Cendron Fernandes - avatar
+ 1
This actually makes alot of sense I always thought the "Satck" can't be deallocated and the variables remains in the stack until the program terminates. thank you Hasty Rei thank you Nicolas
24th Jun 2017, 6:37 AM
Mazin
Mazin - avatar
0
Brother Mazzin try this void Create (Window W, int x, int y) { W.width = x; w.height = y; } int main() { Window W; create (W,800,600) } and let me know if it worked. Happy Trails :)
24th Jun 2017, 12:42 AM
Nicolas Cendron Fernandes
Nicolas Cendron Fernandes - avatar