2

I'm declaring objects of a struct inside of a function and i'd like to access said objects outside of that function (making them global). Here's an example of what i'd like to do

            #include <iostream>
            using namespace std;

            struct exampleStruct
            {
                int ID;
            };

            void makeExampleStruct ()
            {
                exampleStruct exampleObj[30];

                for (int r=0;r<=30;r++)
                {
                    exampleObj[r].ID=r;
                }
            }

            int main()
            {
                makeExampleStruct();
                cout << exampleObj[1].ID << endl;
                return 0;
            }

This gives me a "'exampleObj' was not declared in this scope". I know i could simply declare the objects creation inside of main, but i'd rather keep it inside of a function so it's easier to read. Is there a way of doing that?

Thank you for your help

Coyoteazul
  • 123
  • 1
  • 9

4 Answers4

2

Try to declare the variable globally (outside of the function) use the function to change the global variable.

Variables declared inside of a function are only accessible in that function; they are called local variables as they are local to the function in which they are declared.

The main() function cannot access the local variables of another function.

Globally declared variables are visible everywhere.

Rob Kielty
  • 7,958
  • 8
  • 39
  • 51
kzivic
  • 76
  • 1
  • 4
1

After the function is called, your array no longer exists:

void makeExampleStruct ()
{
    exampleStruct exampleObj[30];
      // exampleObj is created here

    for (int r=0;r<=30;r++)
    {
        exampleObj[r].ID=r;
    }

    // exampleObj is destroyed here.
}

So even if you could access the object, it would be illegal to do so after the function returns, since the object's lifetime has ended.

Vaughn Cato
  • 63,448
  • 5
  • 82
  • 132
0

No. You need to declare it outside the function otherwise it is local.

Steve Harris
  • 5,014
  • 1
  • 10
  • 25
0

You cannot provide global access to local variables from functions. What you can do instead is something like making them static and return a reference:

exampleStruct[30]& makeExampleStruct () {
     static exampleStruct exampleObj[30];
     static bool isinitialized = false;

     if(!isinitialized) {
          for (int r=0;r<=30;r++) {
               exampleObj[r].ID=r;
          }
          isinitialized = true;
     }

    return exampleObj;
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190