using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// compile with: /unsafe;namespace myPerm
{
    class Program
    {
       // delegate void ProcessDelegate(int x, int y);
       
        public unsafe static void swap(int *i, int *j)
        {
           
                int temp = *i;
                *i = *j;
                *j = temp;
        }
 
        static int n=0 ;
        public unsafe static int Perm(int[] a, int k, int m)
        {
           // ProcessDelegate myDelegate = new ProcessDelegate(swap);
            if (k > m)
            {
                
                for (int i = 0; i <= m; i++)
                {
                    Console.Write("  " + a[i] + "  ");
                }
                Console.WriteLine();
                n++;
            }
            else
            {
                for (int i = k; i <= m; i++)
                {
                    swap(&a[k], &a[i]);
                    Perm(a, k + 1, m);
                    swap(&a[k], &a[i]);
                }
            }
            return n;
        }
        static void Main(string[] args)
        {
            int[] list = new int[] { 1, 2, 3, 4, 5 };
           
            int n = Perm(list, 0, 4);            Console.WriteLine("The total are {0} times", n);
            Console.ReadKey();
        }
    }
}

解决方案 »

  1.   

    修改如下:        public unsafe static int Perm(int[] a, int k, int m)
            {
                // ProcessDelegate myDelegate = new ProcessDelegate(swap);
                if (k > m)
                {                for (int i = 0; i <= m; i++)
                    {
                        Console.Write("  " + a[i] + "  ");
                    }
                    Console.WriteLine();
                    n++;
                }
                else
                {
                    for (int i = k; i <= m; i++)
                    {
                        fixed (int* p1 = &a[k], p2 = &a[i])
                        { 
                            //swap(&a[k], &a[i]);
                            swap(p1, p2);
                        }
                        Perm(a, k + 1, m);
                        fixed (int* p1 = &a[k], p2 = &a[i])
                        {
                            //swap(&a[k], &a[i]);
                            swap(p1, p2);
                        }
                    }
                }
                return n;
            } 其他不变。
      

  2.   

    同样学习。fixed语句主要用来防止系统进行“总动内存管理”时移动或释放被某个指针变量所指向的变量。
      

  3.   

    如果我想把整个char[] name 数组变换为char*的话,
    用fixed(char * ptr = name)却是不行。为什么呀?