The code is compiling fine. When I execute I just get the message (Segmentation fault(core dumped)). Any help would be greatly appreciated!
The program is supposed to change the base of the arguments entered. for example ./convert 10 2 5 6 7 input base: 10 Output base: 2 arguments in input base: 5 6 7
I'm just beginning to learn c... any help you could provide would be great! Thanks!
Edited : no longer having issues with segmentation fault. Thank you.
#include <stdio.h>
#include <string.h>
int makeInt(char digits[]) {
int num = 0;
int i = 0;
while (digits[i] != '\0') {
num = num * 10 + (digits[i] - '0');
i++;
}
return num;
}
//converts from original base to base 10
int makeBase10(char digits[],int a) {
int num = 0;
int pow = 1;
int i = 0;
int x = 0;
int length = strlen(digits);
char k;
for (i = length -1; i > -1; i--){
k = digits[i];
if(k <= '9' && k >= '0'){
x = (int)k - '0';
}
else{
x = (int)k - 'a' + 10;
}
num = num + (x*pow);
pow = pow * a;
}
return num;
}
//changes number from base 10 to knew base
// and returns as string
char * toString(char str[], int num, int b) {
int i = 0;
char x;
int mod = 0;
while(0 < num){
mod = num % b;
if(mod < 10 && mod > -1){
x = (char)(num + '0');
}
else{
x = (char)(num - 10 + 'a');
}
str[i] =(int) x;
num = num/b;
}
str[i] = '\0';
int length = i + 1;
int j = 0;
char *reverse;
for(i = length -2; i >= 0; i--){
reverse[i] = str[j];
j++;
}
reverse[length-1] = '\0';
return reverse;
}
int main(int argc, char *argv[]) {
int i;
int num;
int a;
int b;
char str[33]; //binary could be up to 32 + '\0'
a = makeInt(argv[0]); //input base
b = makeInt(argv[1]);; //output base
printf("make int worked and input works");
num = 0;
i = 2;
while (i < argc) {
num = makeBase10(argv[i], a);
printf("%s\n", toString(str, num, b));
i++;
}
}