+ 2

How to store data in structure globally?

Currently I'm studying on structure. i wonder if i get user input in main(), and I stored it inside the sturucture that i have declare outside the main(), Can i access the data of struct in another function? I have tried do the coding, and so far it gives me some random number as the output. https://code.sololearn.com/c64wNp9zaBHk/?ref=app

23rd Jan 2022, 3:51 AM
Shane Nickveen
Shane Nickveen - avatar
3 Antworten
+ 4
That declaration outside of main() is not a declaration, but rather a definition. It defines what the struct will be when you get around to declaring it later, and it does not yet allocate any storage. Every place where you declare struct number num; it does allocate local storage and it has only local scope. The struct is not assigned values in any of the subroutines, so you will see warnings about using uninitialized variables. If you wish to make a global struct, you could turn the definition into a declaration or add a separate declaration in that space outside of main(). Be sure to remove all the local declarations then. struct number{ int x; int y; } num; // make num global Or struct number{ int x; int y; }; struct number num; //global
23rd Jan 2022, 5:34 AM
Brian
Brian - avatar
+ 1
I got it know sir Brian , Thanks for your advise, it works properly now
23rd Jan 2022, 10:30 AM
Shane Nickveen
Shane Nickveen - avatar
+ 1
You are welcome
23rd Jan 2022, 10:41 AM
Brian
Brian - avatar