一个让我彻底疯掉的程序,请一定看一下

littleme741 2001-05-31 09:44:00

//该程序的作用是进行全排列
//比如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;
}
...全文
79 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
littleme741 2001-06-01
  • 打赏
  • 举报
回复
谢谢,你说的很对,不过因为在VC组已经有大虾先解答了,所以不能给你分了,
至于你说的代码写的很糟,我也注意到了,因为只是随便写一下,没有注意风格,你的批评很有道理。
象brianchon致以最崇高的敬意。
brianchon 2001-05-31
  • 打赏
  • 举报
回复
赫赫8也会出错的

我没细看,因为char s[4]并不能容纳"1234",因为后面还有一个字符串结束符0,所以应该定义char s[N+1]

为什么其他没错呢,因为在堆栈上分配空间一般以字长为单位,也就是所谓4字节(一个cpu寄存器的长度)对齐,你定义char s[3]其实分配了4字节,定义char s[5]其实分配了8字节,所以吧你的错误就掩盖了。赫赫!

还有你的排列怎么这么麻烦,应该可以短的多。

70,020

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧