How to store data in structure globally? | Sololearn: Learn to code for FREE!

+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

1/23/2022 3:51:09 AM

Shane Nickveen

3 Answers

New Answer

+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

+1

I got it know sir Brian , Thanks for your advise, it works properly now

+1

You are welcome