Create and access a pointer array

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
C# Code Snippets

C# Source Code Bank

See also …
edit

This C# code snippet creates an unsafe pointer array containing the addresses of structs. Then, it uses the pointer array to access the structs.

WARNING: DO NOT PLAY WITH UNSAFE CODE. If you do not know what you are doing, you can cause any number of costly problems. Use this code at your own risk. They don't call it unsafe for nothing.

class UnsafePointerArray
{
   public struct AStruct
   {
      public int anInteger;
   }
 
   public static void CreatePointerArray()
   {
      AStruct struct0 = new AStruct();
      AStruct struct1 = new AStruct();
      AStruct struct2 = new AStruct();
           
      unsafe
      {
         AStruct*[] StructPtrs = new AStruct*[3];
 
         // load addresses into pointer array
         StructPtrs[0] = &struct0;
         StructPtrs[1] = &struct1;
         StructPtrs[2] = &struct2;
 
         fixed (AStruct** ptrArrayStructPtrs = StructPtrs)
         {
            for (int i = 0; i < 3; i++)
            {
               ptrArrayStructPtrs[i]->anInteger = i * 2;
               Console.WriteLine ("&struct" + i + " = "   
                  + String.Format ("{0:x2}", (int) ptrArrayStructPtrs[i]));
               Console.WriteLine ("&struct" + i + ".anInteger = " 
                  + ptrArrayStructPtrs[i]->anInteger + "\n\n");
            }
         }
      }
   }
}


 Unsafe Pointer Array (program output)
&struct0 = 3afec80

&struct0.anInteger = 0


&struct1 = 3afec7c &struct1.anInteger = 2


&struct2 = 3afec78 &struct2.anInteger = 4

See also


Personal tools