Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

Pointer based stack in c#

By: a guest on Aug 21st, 2012  |  syntax: C#  |  size: 1.96 KB  |  views: 3,588  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. // never do this
  2.  
  3. using System;
  4.  
  5. namespace PointerStack
  6. {
  7.   unsafe struct Node
  8.   {
  9.     public Node* Next;
  10.     public void* Value;
  11.   }
  12.  
  13.   unsafe struct PStack
  14.   {
  15.     public int Count;
  16.     public Node* Head;
  17.   }
  18.  
  19.   unsafe class Program
  20.   {
  21.     static void Main( string[] args )
  22.     {
  23.       PStack* stack = stackalloc PStack[1];
  24.       Node* n1 = stackalloc Node[1];
  25.       Node* n2 = stackalloc Node[1];
  26.       Node* n3 = stackalloc Node[1];
  27.  
  28.       char* a = stackalloc char[3];
  29.       char* b = stackalloc char[3];
  30.       char* c = stackalloc char[6];
  31.  
  32.       // horrible!!!!
  33.       for( int i = 0; i < "One".Length; i++ ) a[i] = "One"[i];
  34.       for( int i = 0; i < "Two".Length; i++ ) b[i] = "Two"[i];
  35.       for( int i = 0; i < "Three".Length; i++ ) c[i] = "Three"[i];
  36.  
  37.       Console.WriteLine("Pushing");
  38.  
  39.       StackPush( stack, n1, a );
  40.       StackPush( stack, n2, b );
  41.       StackPush( stack, n3, c );
  42.  
  43.       Console.WriteLine( "Number of elements on stack: {0}", stack->Count );
  44.       Console.WriteLine("Popping");
  45.  
  46.       char* v;
  47.       while ( (v = (char*)StackPop( stack )) != null )
  48.       {
  49.         Console.WriteLine( "Popped value: {0}", new string(v) );
  50.       }
  51.  
  52.       Console.WriteLine( "Number of elements on stack: {0}", stack->Count );
  53.  
  54.       Console.Read();
  55.     }
  56.  
  57.     private static void* StackPop( PStack* pStack )
  58.     {
  59.       if( pStack == null )
  60.         throw new ArgumentException();
  61.      
  62.       if ( pStack->Count == 0 )
  63.         return null;
  64.  
  65.       Node* node = pStack->Head;
  66.       pStack->Head = node->Next;
  67.  
  68.       pStack->Count--;
  69.  
  70.       return node->Value;
  71.     }
  72.  
  73.     private static void StackPush( PStack* pStack, Node* node, void* value )
  74.     {
  75.       if( pStack == null || node == null || value == null )
  76.         throw new ArgumentException();
  77.  
  78.       node->Value = value;
  79.  
  80.       if( pStack->Head != null )
  81.         node->Next = pStack->Head;
  82.  
  83.       pStack->Head = node;
  84.       pStack->Count++;
  85.     }
  86.   }
  87. }