0

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

Luis Lavieri
  • 4,064
  • 6
  • 39
  • 69

2 Answers2

1

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

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

P.S. It is funny when one answer is marked as the best but the code will be used from other answer.:)

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • My question was about how to correct the infinite loop. @Barmar helped me out with that. I was not asking for the proper algorithm. That is why you don't get the right answer. – Luis Lavieri Oct 25 '14 at 16:37
  • @Luis Lavieri My answer is the most helpful because it shows how the program should be written correctly. It teaches how such programs should be written in C. – Vlad from Moscow Oct 25 '14 at 16:41