tags:

views:

70

answers:

2

hi, i would be happy to know why i got this error for the problem http://www.codechef.com/problems/AXR1P2 in codechef.com and my code is...

#include<stdio.h>
#include<stdlib.h>
int main()
{
int *num=0,n=0,i=0,max=0;char *s="";
int sum[9]={1,5,14,20,25,31,32,38,39},dsum[9]={1,7,8,14,19,25,26,32,33},unitdig=0;
do
{
  gets(s);
*(num+i)=(int)atoi(s);
i++;
}while(*s!='#');
max=i;
for(i=0;i<max-1;i++)
{
 n=*(num+i);
 if(n>10)
  unitdig=33*(n/10-1)+39+dsum[(n%10)-1];
 else
  unitdig=sum[(n%10)-1];
   printf("%d\n",unitdig%10);
}
 getchar();
return 0;}
+3  A: 

Several errors:

char * s = "";
...
gets(s);

you are trying to read into a string literal, you want:

char s[SOMESIZE];

And you have not initialised num to point to anything, so at:

*(num+i)=(int)atoi(s);

you are dereferencing a null pointer. There are probably other issues - these are two I spotted (almost) immediately.

anon
I think the segfault comes at `gets(s)` personally, but that's also a bad one.
Chris Lutz
@Chris Yes, I spotted that immediately after I hit the send button.
anon
Also note that the OP should **never** use `gets()`.
Chris Lutz
A: 

You have an int pointer (num) that does not point to an allocated space. Any access to this pointer will lead to unexpected behavior.

Laurent Etiemble