Can anyone help? I\'m trying to solve problem as my code is working fine on my c
ID: 3924244 • Letter: C
Question
Can anyone help? I'm trying to solve problem as my code is working fine on my complier but doens't work on codecon.. as stated segmentation fault or something I have my code here .. thanks. I think you can go to codecon and look at the questions..
#include
#include
#include
#include
int calc_base(char *);
long long convert(char *, int );
int main()
{
char X[]="";
char Y[]="";
// printf("ask usr 1st ip 0-F: ");
scanf("%s", X);
int baseX = calc_base(X);
long long X_10 = convert(X,baseX);
// printf(" ask usr 2nd ip 0-F: ");
scanf("%s", Y);
int baseY = calc_base(Y);
// printf("baseX %d: ",baseX);
// printf("baseY %d: ",baseY);
long long Y_10 = convert(Y,baseY);
long long Sum = X_10 + Y_10;
printf("%lld ",Sum);
return 0;
}
//************************
int calc_base(char *temp)
{
int base;
char max;
max = *temp;
while(!(*temp == ''))
{
if((*temp) > max)
max = (*temp);
temp++;
}
if(max >= 66 && max <= 71) //if max is a character like A,B, etc.
base = max - 54; //make it decimal
else
base = max - 47; //if max is a digit like 1,2,3, etc.
//printf("usr ip highest base is %d ",base);
//printf("The minimum base required is %d ",base);
if(base<1 && base > 16)
{exit(1);}
else
return base;
}
//************************
long long convert(char *temp,int base)
{
long long decimal = 0;
int i , val, len;
len = strlen(temp) - 1;
for(i=0 ; temp[i] != '' ; i++)
{
switch(temp[i])
{
case '0':
val = 0;
break;
case '1':
val = 1;
break;
case '2':
val = 2;
break;
case '3':
val = 3;
break;
case '4':
val = 4;
break;
case '5':
val = 5;
break;
case '6':
val = 6;
break;
case '7':
val = 7;
break;
case '8':
val = 8;
break;
case '9':
val = 9;
break;
// case 'a':
case 'A':
val = 10;
break;
// case 'b':
case 'B':
val = 11;
break;
// case 'c':
case 'C':
val = 12;
break;
// case 'd':
case 'D':
val = 13;
break;
// case 'e':
case 'E':
val = 14;
break;
// case 'f':
case 'F':
val = 15;
break;
}
decimal += val * pow(base, len);
len--;
}
return decimal;
}
Explanation / Answer
Change this declaration of variables
char X[]="";
char Y[]="";
to
char X[70];
char Y[70];
X and Y will maximum hold 70 characters . long long value should be able to fit in that.
You should be gettng segmentation error because initalially x and y have less memory 1 character for null terminator but later when user inputs values, it occupies bigger space. So change the declarations as mentioned above and the problem should be resolved. Please do comment/rate the answer if problem is resolved thanks.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.