Hello all. This is definitly the best site for help on c projects. ( Looking at Adak, Laserlight, Grumpy ....) The program description is in the comment at the head of the source code. Basically it converts any integer from base 10 into a base of the user's choosing. Im having a problem at line 54 when I set variable "J" to "strlen( s ) -1". It returns -1, which means its reading my string as zero. Any suggestions?
Code:
/* Write a function itob(n,s,b) that converts the integer
* n into a base b character representation in the string
* s. In particular, itob(n,s,16) formats n as a hexadecimal
* integer in s.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void itob( int , char * , int );
int strtoi( char * );
void reverse( char * );
char * find_space( int , int );
int main( int argc , char **argv ){
if( argc != 3 )
/* expects two arguments, num and new base */
printf( "Usage: %s n b\nConvert base-10 number [n] into base-[b] number\n" , argv[ 0 ] );
else{
int n , b;
char * string = NULL;
if( !( n = strtoi( argv[ 1 ] ) ) || !( b = strtoi( argv[ 2 ] ) ) )
puts( "Invalid integer(s) has been detected...abort" );
else{
string = find_space( n , b );
itob( n , string , b );
printf( "%s\n" , string );
getchar();
}
}
return 0;
}
int strtoi( char * str ){
int n , i;
for( i = 0 , n = 0;str[ i ] != '\0' && str[ i ] <= '9' && str[ i ] >= '0' ; ++i )
n = n * 10 + ( str[ i ] - '0' );
return ( str[ i ] == '\0' ) ? n : 0;
}
void itob( int n , char * string , int b ){
int i , r;
for( i = 0;n > 0; ++i ){
string[ i ] = ( r = n % b ) ;
n /= b;
}
string[ i ] = '\0';
reverse( string );
return;
}
void reverse( char * s ){ // taken from K&R, pg 63.
int c , i , j;
for( i = 0 , j = strlen( s ) - 1; i < j; ++i , --j )
c = s[ i ] , s[ i ] = s[ j ] , s[ j ] = c;
return;
}
char * find_space( int n , int b ){
int i;
char * string;
for( i = 1;n > 0;++i ) // EDIT: changed i = 0 to i = 1 , counting , not using array indexing
n /= b;
string = malloc( ( sizeof( char ) * i ) + 1 );
return string;
}
EDIT: I know i dont free my malloc string, not worried about that right now