29.8 Passing pointers to methods


29.8 Passing pointers to methods

Let's put together what we have learnt so far, and take a look at a general example of how pointers are passed between methods.

Examine this program:

 1: using System;  2:  3: class TestClass{  4:  5:   static unsafe void PerformOp (  int* pX  ){  <-- 1  6:     *  pX  =  99;   <-- 2  7:   }  8:  9:   public static unsafe void Main(){ 10:     int a = 1; 11:     Console.WriteLine("a was :" + a); 12:  PerformOp (&a);   <-- 3  13:     Console.WriteLine("a is :" + a); 14:   } 15: } 

(1) Method takes in a parameter of type int* , a pointer

(2) Uses indirection to change the int value stored at the address in pX

(3) Invoke method by passing in the address of an int variable.

Output:

 c:\expt>test a was :1 a is :99 

In the example above, the PerformOp method (lines 5 “ 7) is marked with the unsafe modifier. It takes in a pointer to an int , dereferences the pointer to obtain the address where the int is stored, and stores the value 99 there.

Main has to be marked as unsafe too because it uses the indirection operator to get the address of local int variable a . The output shows that local variable a has been altered by PerformOp .



From Java to C#. A Developers Guide
From Java to C#: A Developers Guide
ISBN: 0321136225
EAN: 2147483647
Year: 2003
Pages: 221
Authors: Heng Ngee Mok

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