Please help me fix my code..
It works in CodeBlocks but when I try in Linux, it says it has an error -
SEGMENTATION FAULT (core dumped)
:(

This program converts between bases of a number.
After it converts a number it should go back to start to get input again..

#include<stdio.h>
#include<stdlib.h>

typedef char string[64];

//Converting the character to integer
int charToInt(char ch){
    if(ch>=48 && ch<=57)
        return (int)(ch-48);
    if(ch>=65 && ch<=90)
        return (int)(ch-55);
}

//Converting the integer to character
char intToChar(int x){
    if(x>=0 && x<=9)
        return (char)(x+48);
    if(x>=10 && x<=35)
        return (char)(x+55);
}


int main(){
    int currentBase = 0, targetBase = 0;
    int digit = 0, decimal = 0, multiplier = 1;
    int i, index, result;
    char final;
    string input = "", output = "";

    printf("Enter the number to be converted:\n");
    scanf("%s", input);

    printf("Enter the current base of the number:\n");
    scanf("%d", &currentBase);

    //Checking if the current base is correct
    if(currentBase<2 || currentBase>36){
        printf("Base 2 to 36 is only allowed.\n\n");
        return main();
    }

    printf("Enter the target base of the number:\n");
    scanf("%d", &targetBase);

    //Checking if the target base is correct
    if(targetBase<2 || targetBase>36){
        printf("Base 2 to 36 is only allowed.\n\n");
        return main();
    }


    //Converting the input to base 10
    for(i=strlen(input)-1; i>=0; i--){
        digit = charToInt(input[i]);

        if(digit>=currentBase){
            printf("Invalid number!\n\n");
            return main();
        }

        decimal += digit*multiplier;
        multiplier *= currentBase;
    }


    //Converting the decimal to the target base
    while(decimal > 0){
        result = decimal % targetBase;
        decimal /= targetBase;
        final = intToChar(result);
        output[index] = final;
        index++;
    }


    printf("Result:\n");
    //Printing the output in reverse order
    for(i=strlen(output)-1; i>=0; i--){
        printf("%c", output[i]);
    }


    printf("\n\n");
    return main();

}

Recommended Answers

All 3 Replies

1. I mainly post in the Java section because I'm a Java developer and rarely use C
2. don't PM people at random to get your code fixed, just wait untill someone who can actually help you responds.

The program seems to be fine. Except that, the variable index in line number 26 wasn't initialised to 0(but was used to index an array).
It works fine after that change.

return main();

This makes no sense. It turns the program into a never-ending recursion that will eventually run out of stack and crash. Do not call main() from within your program.

commented: Oh yeah. +6
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.