【发布时间】:2018-04-17 17:04:25
【问题描述】:
所以我有一个程序来查找整数 N 可以表示为“n”个整数之和的方式总数。 例如,10 可以表示为 2,3 和 5 的组合如下-
10 = 5 + 5
10 = 5 + 3 + 2
10 = 3 + 3 + 2 + 2
10 = 2 + 2 + 2 + 2 + 2
#include<stdio.h>
#include<stdlib.h>
int ways(int,int*,int);
int main() {
int n,num; //n is number of possible integers
scanf("%d",&n);
int*curr=(int*)malloc(n*sizeof(int)); //dynamically allocated array that stores all "n" integers in array form
for(int i=0;i<n;i++) {
scanf("%d",curr+i);
}
int t,N; //t is number of test cases
scanf("%d",&t);
while(t--) {
scanf("%d",&N); //for each test case, scans the number N that needs to be expressed as a sum of combinations those "n" integers
num=ways(N,curr,n);
printf("%d\n",num);
}
return 0;
}
int ways(int N,int*p,int size) {
int flag=1;
for(int i=0;i<size;i++) {
if(N/(*(p+i))!=0) {
flag=0;
break;
}
//Above loop says that if number N is less than all of the "n" integers, it
cannot be expressed as their sum. Hence, 0 will be returned if flag is 1
}
if(flag==1)
return 0;
if(N==0)
return 1;
int num=0,temp;
for(int i=0;i<size;i++) {
temp=*(p+i);
num=num+ways(N-temp,p,size); //GETTING RUNTIME ERROR AT THIS LINE
}
return num;
}
即使递归深度非常小,程序在递归函数调用时也会出现 SIGSEGV 错误
【问题讨论】:
-
最好提供导致崩溃的输入...有很多scanf,我们无法猜测所有...
-
一旦我们到达特定的行,所有输入都会崩溃。
-
你对我的口味有太多的猜测。您想至少解释所有要输入的值吗?年龄?重量? “n”个?
-
不要写
*(p+i)。只需改用p[i]。否则你只会让阅读变得痛苦。
标签: c recursion segmentation-fault runtime-error