Reputation: 46
#include<stdio.h>
#include<string.h>
#include<malloc.h>
char *sum(char nn1[],char nn2[]){
int i,j,s,max=0,c=0,reslen=0;
max=(strlen(nn2)>strlen(nn1))?strlen(nn2):strlen(nn1);
char *str=(char*)malloc(max+1);
char n1[max],n2[max];
char st[max+1];
for(i=0;i<max;i++){
n1[i]='0';n2[i]='0';
}
for(i=max-strlen(nn1),j=0;j<strlen(nn1);j++){
n1[i]=nn1[j];
i++;
}
for(i=max-strlen(nn2),j=0;j<strlen(nn2);j++){
n2[i]=nn2[j];
i++;
}
for(i=max-1;i>=0;i--){
s=(n1[i]-'0')+(n2[i]-'0')+c;
st[i+1]=s%10+'0';
c=s/10;
}
if(c){
reslen=max+1;
st[0]='1';
}else{
reslen=max;
for(i=0;i<=max;i++)
st[i]=st[i+1];
st[i]='\0';
}
for(i=0;i<reslen;i++){
str[i]=st[i];
}
if(strlen(str)!=reslen){
str[reslen]='\0';
}
return str;
}
int main()
{
unsigned int n,i;
scanf("%d",&n);
char *s0=sum("0","0");
char *a[n];
a[n]=malloc(10000);
for(i=0;i<n;i++)
scanf("%s",a[i]);
for(i=0;i<n;i++)
s0=sum(s0,a[i]);
printf("%s",s0);
return 0;
}
The above program closes unexpectly. I run this program in gcc, first scan no. of input and then scan numbers in string format and then perform sum function. Please fix error.
The sum function working fine without scanf() in main function, but it closes when using it with scanf().
Upvotes: 0
Views: 44
Reputation: 4044
a
is not allocated properly
You should allocate it in the loop prior to taking input in it with scanf
a[n]=malloc(10000);// remove this statement, a[n] is out of bound too
for(i=0;i<n;i++)
{
a[i] = malloc(10000); // allocate inside loop
scanf("%s",a[i]);
}
Upvotes: 2