【发布时间】:2016-05-08 21:21:48
【问题描述】:
#include <stdio.h>
#define ARRAY_LEN 45
int howmany (int table[] , int number , int frequency , int index) {
if (index <= ARRAY_LEN) {
if (table[index] == number) {
frequency++;
}
howmany(table , number , frequency , index++);
}
return frequency;
}
int main(void) {
int array[] = {9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,9,8,7,6,5,4,3,4,5,6,7,8,9,9,8,7,6,5,6,7,8,9,9,8,7,8,9,9};
int frequency = 0;
int chosen;
printf("Select chosen number\n");
scanf("%d" , &chosen);
frequency = howmany(array ,chosen ,frequency , 0);
printf("Frequency of %d is %d times.\n" , chosen , frequency);
return 0;
}
所以我明天有一个考试,我遇到了这个简单的程序的问题,该程序用递归计算一个数字在表中找到的次数。请帮助我找到问题,因为调试器在我调用函数 howmany 的行中发现了问题,但是我似乎无法检测到它是什么。谢谢
【问题讨论】:
-
这个程序有什么问题?你期望它做什么?它实际上是做什么的?
-
考虑
index++的值是多少。它是index在递增之前的原始值,这意味着您在所有调用中看到index的相同值。段错误意味着程序的堆栈空间不足。在这里,您实际上并不需要在函数中增加index。说出你的意思:index + 1. -
当
howmany递归调用howmany时,为什么会把返回值扔掉呢?那有什么用?为什么将frequency传递给howmany?为什么不只是让它返回频率?没有 cmets,很难理解这段代码。 -
病得很厉害,试着解释一下。该表有 45 个数字,howmany 函数试图找出变量数字在表中存在的次数。索引变量用于在表中作为计数器运行,这就是我增加它的原因。所以我检查了桌子的每个位置,直到 44 位。
-
ΥΕΑΗ M.Oehm 你是对的,谢谢 :) 我没有注意到它是后缀,谢谢!另外关于频率的返回,我实际上返回了它,我只是在修复它之前上传了该程序的早期版本。谢谢大卫·施瓦茨。
标签: c arrays recursion segmentation-fault