[英]I am getting an Memory fault(coredump) error message in my c program?
I am not able to understand why it is showing this error. 我无法理解为什么显示此错误。 I have never encountered such an error before. 我以前从未遇到过这样的错误。 Here is my code, can you identify the mistake or the cause of it : 这是我的代码,您能否确定错误或原因:
#include<stdio.h>
#include<math.h>
void dec2bin(int n,int bin[1000]){
int num = 0, index = 0, i;
while (n != 0){
bin[index] = n%2;
index++;
n = n/2;
}
}
int Sub(int a[100],int b[1000],int ac[100],int siz){
int i=siz-1,k=0;
for(;i>=0;i--){
if(b[i]){
a[k++]=ac[siz-i-1];
}
}
return k;
}
int sum(int a[100],int s){
int i,sum=0;
for(i=0;i<s;i++)
sum+=a[i];
return sum;
}
main(){
int b[1000],sub[100],a[100],n,i,s,count=0;
printf("Enter n: ");
scanf("%d",n);
for(i=0;i<n;i++){
printf("Enter number %d",i+1);
scanf("%d",&a[i]);
}
printf("Enter S: ");
scanf("%d",s);
int no=(int)pow(2.0,(float)n);
for (i=0;i<1000;i++)
b[i]=0;
for(i=0;i<no;i++){
dec2bin(i,b);
int siz=Sub(sub,b,a,n);
if(sum(sub,siz)==s)
count++;
}
printf("Subsets: %d",count);
}
And this code shows memory fault error immediately after entering the value of n
. 并且此代码在输入n
值后立即显示内存错误错误。
You're using scanf
slightly incorrectly. 您使用的scanf
略有错误。
The arguments following the format string need to be pointers to your objects, not the objects themselves. 格式字符串后面的参数需要是对象的指针,而不是对象本身的指针。
scanf("%d", &n);
Do remember though, that scanf is very dangerous to use. 不过请记住,使用scanf非常危险。 Behavior is undefined for instance if the integer would overflow. 例如,如果整数溢出,则行为未定义。 Better to read a line safely then use strtol
to parse it, since you can detect errors properly. 最好安全地读取一行,然后使用strtol
进行解析,因为您可以正确检测到错误。
when taking input for n. 当输入n时。
scanf("%d", &n);
You forgot a &
您忘记了&
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.