If you need to consider negative numbers, you may need additional logic. In fact, when you play with arrays, you donβt know the size of the advance, you can do some more security checks, and adding an API to process the data structure is also very convenient.
// returns the number of digits converted // stores the digits in reverse order (smalles digit first) // precondition: outputdigits is big enough to store all digits. // int convert( int number, int* outputdigits, int* signdigit ) { int* workingdigits = outputdigits; int sign = 1; if( number < 0 ) { *signdigit = -1; number *= -1; } ++workingdigits; for ( ; number > 0; ++ workingdigits ) { *workingdigits = number % 10; number = number / 10; } return workingdigits - outputdigits; } void printdigits( int* digits, int size, int signdigit ) { if( signdigit < 0 ) printf( "-" ); for( int* digit = digits+size-1; digit >= digits; --digit ){ printf( "%d", *digit ); } } int main() { int digits[10]; int signdigit; printdigits( digits, convert( 10, digits, &signdigit ), signdigit ); printdigits( digits, convert( -10, digits, &signdigit ), signdigit ); printdigits( digits, convert( 1005, digits, &signdigit ), signdigit ); }
xtofl
source share