// never do this
using System;
namespace PointerStack
{
unsafe struct Node
{
public Node* Next;
public void* Value;
}
unsafe struct PStack
{
public int Count;
public Node* Head;
}
unsafe class Program
{
static void Main( string[] args )
{
PStack* stack = stackalloc PStack[1];
Node* n1 = stackalloc Node[1];
Node* n2 = stackalloc Node[1];
Node* n3 = stackalloc Node[1];
char* a = stackalloc char[3];
char* b = stackalloc char[3];
char* c = stackalloc char[6];
// horrible!!!!
for( int i = 0; i < "One".Length; i++ ) a[i] = "One"[i];
for( int i = 0; i < "Two".Length; i++ ) b[i] = "Two"[i];
for( int i = 0; i < "Three".Length; i++ ) c[i] = "Three"[i];
Console.WriteLine("Pushing");
StackPush( stack, n1, a );
StackPush( stack, n2, b );
StackPush( stack, n3, c );
Console.WriteLine( "Number of elements on stack: {0}", stack->Count );
Console.WriteLine("Popping");
char* v;
while ( (v = (char*)StackPop( stack )) != null )
{
Console.WriteLine( "Popped value: {0}", new string(v) );
}
Console.WriteLine( "Number of elements on stack: {0}", stack->Count );
Console.Read();
}
private static void* StackPop( PStack* pStack )
{
if( pStack == null )
throw new ArgumentException();
if ( pStack->Count == 0 )
return null;
Node* node = pStack->Head;
pStack->Head = node->Next;
pStack->Count--;
return node->Value;
}
private static void StackPush( PStack* pStack, Node* node, void* value )
{
if( pStack == null || node == null || value == null )
throw new ArgumentException();
node->Value = value;
if( pStack->Head != null )
node->Next = pStack->Head;
pStack->Head = node;
pStack->Count++;
}
}
}