一个让我彻底疯掉的程序,请一定看一下
//该程序的作用是进行全排列
//比如N=3的时候,对123进行全排列
//用递归的方法实现的。
//但当N=4的时候,系统就出错,其他任何N都正常,why?
//我的编译器是VC6.0,没有加任何Service Pack
//在Windows 2000 professional版本下。
//请诸位大侠一定要出手,我简直活不了了,难道这编译器有问题???
#include <stdlib.h>
#include <string.h>
#include <iostream.h>
const int N=5; //当N为其他数,比如3,5,6等结果均正常,就是在4的时候出错
//难道是VC编译器的问题。
void Chunk(char* a,int x);
void strGet1(char* a,int iend,char* s);
void strGet2(char* a,int ibeg,char* s);
long shit;
int main()
{
char myA[N];
strcpy(myA,"1");
Chunk(myA,2);
cout<<"total:"<<shit<<endl;
return 0;
}
//a表示当前已有的排列,x表示下一个要加到排列中的数
//原理是把新的一个数,插入到当前已有的排列中去,比如
//当前有排列为12,则产生三种情况312,132和123
void Chunk(char* a,int x)
{
char newA[N];
char newS[1];
char temp[N];
char str1[N];
char str2[N];
int i;
int k=strlen(a);
if(k==N)
{
cout<<a<<endl;
shit=shit+1;
}
else
{
strcpy(temp,a);
itoa(x,newS,10);
strcpy(newA,newS);
strcat(newA,temp);
strcpy(temp,newA);
Chunk(temp,x+1);
int m=strlen(a)-2;
for(i=0;i<=m;i++)
{
strcpy(temp,a);
itoa(x,newS,10);
strcpy(str1,"");
strcpy(str2,"");
strGet1(a,i,str1);
strGet2(a,i+1,str2);
strcpy(temp,str1);
strcat(temp,newS);
strcat(temp,str2);
Chunk(temp,x+1);
}
strcpy(temp,a);
itoa(x,newS,10);
strcpy(temp,a);
strcat(temp,newS);
Chunk(temp,x+1);
}
}
void strGet1(char* a,int iend,char *s)
{
int i;
for(i=0;i<=iend;i++)
s[i]=a[i];
s[i]=0x00;
}
void strGet2(char* a,int ibeg,char* s)
{
unsigned int i;
for(i=ibeg;i<strlen(a);i++)
s[i-ibeg]=a[i];
s[i-ibeg]=0x00;
}