【发布时间】:2013-02-27 21:38:18
【问题描述】:
我正在编写一个程序,该程序将取一个 1-10 之间的数字并显示所有可能的数字排列方式。
前 输入:3 输出:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
每当我输入 9 或 10 时,程序都会给出分段错误并转储内核。我相信问题是我的递归算法被调用了太多次。有人可以帮助指出我如何限制必要的递归调用量吗?这是我当前的代码:
void rearange(int numbers[11], int index, int num, int fact) {
int temp = numbers[index];
numbers[index] = numbers[index-1];
numbers[index-1] = temp;
int i;
for (i = 1; i <= num; ++i) // print the current sequence
{
printf("%d ", numbers[i]);
}
printf("\n");
fact--; // decrement how many sequences remain
index--; // decrement our index in the array
if (index == 1) // if we're at the beginning of the array
index = num; // reset index to end of the array
if (fact > 0) // If we have more sequences remaining
rearange(numbers, index, num, fact); // Do it all again! :D
}
int main() {
int num, i; // our number and a counter
printf("Enter a number less than 10: ");
scanf("%d", &num); // get the number from the user
int numbers[11]; // create an array of appropriate size
// fill array
for (i = 1; i <= num; i++) { // fill the array from 1 to num
numbers[i] = i;
}
int fact = 1; // calculate the factorial to determine
for (i = 1; i <= num; ++i) // how many possible sequences
{
fact = fact * i;
}
rearange(numbers, num, num, fact); // begin rearranging by recursion
return 0;
}
【问题讨论】:
-
GDB 应该告诉您 seg-fault/core 转储发生在哪里,以及崩溃发生时堆栈的深度。它说什么?
-
事实变量显示剩余的迭代次数。输入 9 时,程序崩溃时还剩下 188202 次迭代。它说它发生在
printf()语句期间。 -
您正在避免使用 GDB。在编程中使用调试器是必不可少的。如果你有一个核心文件,你真的应该学会在 GDB 中加载它并检查堆栈深度和崩溃位置等内容。
-
@Slayter 不知道您是否还在那里,但请尝试我在“编辑 2”中编写的代码:它解决了您的问题,递归深度等于项目数(例如 10) .
-
我使用 GDB 来获取该信息
标签: c recursion segmentation-fault sequence coredump