9.6 Functions and Arguments as Pointers


9.6 Functions and Arguments as Pointers

The previous chapter demonstrated pointers, which are variables that represent the memory addresses of other variables. Given a memory address, we've already seen how it's possible to not only resolve that address so we can see which value is stored there, but we can also assign a value to that address using the indirection operator (*) as though the value were assigned to the variable directly by name. Like this:

      int variable = 0;      int *pointer = &variable;      *pointer = 5;     //variable now equals 5 

Furthermore, given what we know about functions we know that a local variable cannot be accessed outside of its owning function. So, as shown in the following code, the local scope variable from function1 cannot be accessed in function2.

      void function1()      {         int variable;     //has local scope         function2();      }      void function2 ()      {         return;      } 

However, if function1 calls function2, then function1 has still not terminated and its memory is therefore not destroyed. Function1 cannot proceed until function2 completes. Thus, while function2 is being executed, function1 is still "alive." Though it is not possible for function2 to access the local variables of function1 directly by name, like it can with its own local variables, it is possible for function1 to pass pointers of its local variables as arguments to function2. Function2 can then resolve those pointers and access the memory locations of those variables in function1.

Consider the following code:

      void function1()      {         int variable = 5;         function2(&variable);      }      void function2 (int *var)      {         *(var) = 10;    //Function1.variable now is 5      return;      } 




Introduction to Game Programming with C++
Introduction to Game Programming with C++ (Wordware Game Developers Library)
ISBN: 1598220322
EAN: 2147483647
Year: 2007
Pages: 225
Authors: Alan Thorn

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net