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
5 Respostas
+ 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().
+ 1
thank you Nicolas but unfortunately it didn't work same weird output:
1
-1226127952
+ 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
+ 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
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 :)