Here is another solution (I used the function that user1089679 posted above and addressed the comments that most other users have made). Any feedback on the i_to_a function (and ideally on the whole program) would be appreciated. Please feel free to be as critical and detailed as you want (if you are nice while doing it, would be great too :)):
#include <stdlib.h>
#include <stdio.h>
int no_of_digits( int num, int radix );
char *i_to_a( char *str, int digit_count, int num, int radix );
int main()
{
int num, radix;
printf( "Enter a decimal number: " );
scanf( "%d", &num );
printf( "Enter radix: " );
scanf( "%d", &radix );
int digit_count = no_of_digits( num, radix );
char *str = malloc( sizeof( char ) * ( digit_count + 1 ) );
if( str == NULL )
{
printf( "Malloc failed in main, exiting.\n" ); //do additional error handling as needed
return 0;
}
str = i_to_a( str, digit_count, num, radix );
printf( "\nThe converted number as a string is: %s\n", str );
free( str );
return 0;
}
int no_of_digits( int num, int radix )
{
int digit_count = 0;
if( num < 0 )
digit_count++;
while( num != 0 )
{
digit_count++;
num /= radix;
}
return digit_count;
}
char *i_to_a( char *str, int digit_count, int num, int radix )
{
if( num == 0 )
{
*str = '0';
return str;
}
if( num == -2147483648 )
{
str[0] = '-';
str[1] = '1';
for( size_t i = 2; i < digit_count; ++i )
str[i] = '0';
return str;
}
if( num < 0 )
{
num = -1 * num;
str[0] = '-';
}
str[digit_count] = '\0';
while( num > 0 )
{
str[digit_count-1] = num % radix + '0';
num /= radix;
digit_count--;
}
return str;
}
atoiwould be useless, because it converts ASCII to integer, not vice versa.itoaand notatoi