gpt4 book ai didi

没有 printf,C for 循环无法正常工作

转载 作者:太空宇宙 更新时间:2023-11-04 01:01:12 25 4
gpt4 key购买 nike

我想列出 n 个数字的所有排列。到现在为止一切似乎都很正常,但我遇到了一个非常奇怪的行为。使用此代码:

int **liste_permutations(int n){
int i, fact = factorielle(n);
int **tab=malloc(sizeof(int*)*fact);
for(i=0; i<fact; ++i)
{
tab[i] = malloc(sizeof(int)*n);
}
for(i=0;i<n;++i)
{
tab[0][i] = n-i;
}

for(i=1;i<fact;++i)
{
tab[i] = next_permutation(tab[i-1], n);
printf(" ");
}
return tab;}

这个main()的输出

    int **tab;
tab = liste_permutations(3);
for(i=0; i<factorielle(3); ++i)
{

for(j=0; j<3; ++j)
{
printf("%d", tab[i][j]);
}
printf("\n");
}

          321
231
213
312
132
123

但是如果我把它改成

int **liste_permutations(int n){
int i, fact = factorielle(n);
int **tab=malloc(sizeof(int*)*fact);
for(i=0; i<fact; ++i)
{
tab[i] = malloc(sizeof(int)*n);
}
for(i=0;i<n;++i)
{
tab[0][i] = n-i;
}

for(i=1;i<fact;++i)
{
tab[i] = next_permutation(tab[i-1], n);
}
return tab;}

主要的输出是:

321
231
321
231
321
231

例如,如果我尝试使用 n=5 执行此操作,则输出为空白(可能是因为它尝试输出 125 "")

这是 next_permutation 代码:

int *next_permutation(int *t, int n){
//printf("n = %d\n", n);
int i, max, count;
for(i=0;(i<n) && (max !=i); ++i)
{
if(t[i] == n)
{
max = i;

}
if(t[i] == (t[i-1]+1))
{
++count;
if(count == (n-1))
{
return NULL;
}
}

}
//printf("max = %d\n", max);
if(n==1)
{
//printf("n=1\n");
return NULL;
}
int *next = malloc(n);
if(max == n-1)
{
//printf("max == n-1\n");
int *s;
s = malloc(sizeof(int));
for(i=0; i<(n-1);++i)
{
s[i]=t[i];
}
for(i=0; i<n-1; ++i)
{
//printf("%d", s[i]);
}
//printf("\n");
s = next_permutation(s, n-1);
if(s == NULL)
{
//printf("NUUUUUUl");
// next = NULL;
return NULL;
}
//printf("reprise en n = %d\n", n);
for(i=1;i<n;++i)
{
next[i] = s[i-1];
}
//printf("\n");
free(s);
next[0]=n;
return next;
}
else
{
//printf("max != n-1\n");

for(i=0; i<n; ++i)
{
next[i] = t[i];
}
int tmp = next[max];
next[max] = next[max+1];
next[max+1] = tmp;
for(i=0;i<n;++i)
{
//printf("%d", next[i]);
}
//printf("\n");
return next;
}}

编辑:修改了第 2 条评论所说的内容,但我仍然有 sam 问题。

EDIT2:感谢所有帮助过我的人!尤其是 mweerden,他向我展示了正确的路径(这是因为计数未初始化)!

最佳答案

tab[i] = malloc(sizeof(int*)*n);

tab[i] 想要一个 int 数组(不是 int* 数组)

更改为

tab[i] = malloc(sizeof(int)*n);

还有

int *s;
for(i=0; i<(n-1);++i)
{
s[i]=t[i];
}

你没有为s保留空间(未初始化使用)

关于没有 printf,C for 循环无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38931494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com