Reputation:
I have written the following program for changing a decimal number into a number of any other base less than or equal to 16.
I keep getting a segmentation fault. I am not able to figure out my mistake. Please help me solve this issue.
Program:
#include<stdio.h>
#include<string.h>
void reverse(char s[]){
int c,i,j;
for (i=0,j=strlen(s)-1;i<j;i++,j++){
c= s[i];
s[i]=s[j];
s[j]=c;
}
}
void itob(int n, int b){
int i=0,index;
char s[50];
char s2[17]="0123456789ABCDEF";
index = n % b ;
do {
s[i++]=s2[index];
} while((n/=b)>0);
s[i]='\0';
reverse(s);
printf("%s\n",s);
}
int main (void){
int n,b;
char s[50];
printf("enter the number");
scanf("%d",&n);
printf("enter the base");
scanf("%d",&b);
itob(n,b);
return 0;
}
Upvotes: 1
Views: 42
Reputation: 20244
This:
for (i=0,j=strlen(s)-1;i<j;i++,j++){
c= s[i];
s[i]=s[j];
s[j]=c;
}
is an infinite loop. You probably wanted:
for (i = 0, j = strlen(s) - 1; i < j; i++, j--){ /* j-- instead of j++ */
c = s[i];
s[i] = s[j];
s[j] = c;
}
You have a logical error. This
index = n % b ;
do {
s[i++]=s2[index];
} while((n/=b)>0);
should be
do {
index = n % b;
s[i++] = s2[index];
} while((n /= b) > 0);
Upvotes: 1