简体   繁体   中英

segmentation fault when running number converter program

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;
}

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM