Even though I have more experience with higher level languages, I am having a lot of troubles understanding how memory allocation
and how strings
really work in C
.
I am trying to implement a very simple base converter that works recursively. The only thing is that it should return a char*
instead of an int
Here is my code. I already tested the recursive calls and it works if I use integers. So, the problem is definitely with the string part. It gives me an infinite loop.
char* baseConversion(int num, int baseIn, int baseOut){
//convert num to base ten
int quotient = num / baseOut;
int remainder = num % baseOut;
char rem = (char)(((int)'0') + remainder);
char *result = malloc(strlen(output) + 1);
strcpy(result, rem);
if (quotient == 0)
return result;
else
return strcat(result, baseConversion(quotient, baseIn, baseOut));
}
Many thanks