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
Change:
strcpy(result, rem);
to:
result[0] = rem;
result[1] = 0;
This will create a single-character string containing the character in rem
.
You also may need to fix:
malloc(strlen(output)+1)
as there's no variable named output
in your function.
If I have understood correctly what you are saying about then what you need is the following
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * baseConversion( unsigned int x, unsigned int base )
{
unsigned int digit;
char *p = NULL;
size_t n = 2;
if ( base > 10 || base < 2 ) base = 10;
digit = x % base;
if ( x / base ) p = baseConversion( x / base, base );
if ( p ) n += strlen( p );
p = realloc( p, n );
*( p + n - 2 ) = digit + '0';
*( p + n - 1 ) = '\0';
return p;
}
int main(void)
{
unsigned int x = 255;
char *p = baseConversion( x, 10 );
printf( "%s\n", p );
free( p );
p = baseConversion( x, 8 );
printf( "%s\n", p );
free( p );
p = baseConversion( x, 2 );
printf( "%s\n", p );
free( p );
return 0;
}
The output is
255
377
11111111
PS It is funny when one answer is marked as the best but the code will be used from other answer.:)
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.