Search code examples
ccharreversec-stringsfunction-definition

Operation on string inside function


Why does putting reverse() inside main() print 12345 while putting reverse() as the last statement of itoa() definition produces 54321?

#include <stdio.h>
#include <string.h>

void itoa(long n, char *s);
void reverse(char *s);

int main() {

    int n = 12345;
    char s[10];
    itoa(n, s);
    printf("%s\n", s);
    return 0;
}

void itoa(long n, char *s) {

    int i;
    while (n != 0) {
      *s++ = n % 10 + '0';
      n /= 10;
    }
    *s = '\0';
    reverse(s);
}

void reverse(char *s) {

    int i, temp, len = strlen(s);
    for (i = 0; i < len / 2; i++) {
      temp = s[len - 1 - i];
      s[len - 1 - i] = s[i];
      s[i] = temp;
    }
}   

I expected the output to be the same, since (I think, at least) I'm passing pointers as arguments to both functions.


Solution

  • After the while loop within the function itoa

    void itoa(long n, char *s) {
    
        int i;
        while (n != 0) {
        *s++ = n % 10 + '0';
        n /= 10;
        }
        *s = '\0';
        reverse(s);
    }
    

    the pointer s points to the zero character '\0' of the string. So the function reverse reverses nothing.

    You need to use an intermediate pointer in the function itoa and pass the original pointer to the function reverse.

    Pay attention to that the parameter of the function itoa should be an unsigned integer type because the function does not take into account the sign of its argument.

    Also the function does not process an argument equal to 0.

    The function can look the following way

    char * itoa( unsigned int n, char *s ) 
    {
        const unsigned int Base = 10;
    
        char *p = s;
    
        do
        {
            *p++ = n % Base + '0';
        } while ( n /= Base );
    
        *p = '\0';
    
        return reverse( s );
    }
    

    and the function reverse will look as

    char * reverse( char *s ) 
    {
        for ( size_t i = 0, n = strlen( s ); i < n / 2; i++ ) 
        {
            char c = s[n - 1 - i];
            s[n - 1 - i] = s[i];
            s[i] = c;
        }
    
        return s;
    }