Search code examples
ccharreversec-stringsfunction-definition

How to reverse a string with pointers only?


I'm trying to reverse a string, but it just stays the same. I don't use any modules except <string.h> and <stdio.h>.

void rev(s){
    char i, temp;
    char *sf = s;
    char ri = strlen((s) - 1);
    char *sl = &s[ri];
    for (i = 0; i < ri; i++){
        if (*sf != *sl){
            temp = *sf++;
            s[i] = *sl--; //
            s[ri--] = temp; //those two seems to be getting new characters, but it won't
        }
        else {
            ri--;
            sf++;
            sl--;
        }
    }
    printf("%s", s);
}

Solution

  • The function will not compile at least because the parameter does not have a type specifier.

    void rev(s){
    

    The type char has a little range of acceptable values. So you shall not use it for calculating the length of a string.

    The call of strlen in this declaration

    char ri = strlen((s) - 1);
    

    invokes undefined behavior. It seems you mean

    char ri = strlen(s) - 1; 
    

    that also can invoke undefined behavior for an empty string.

    This loop

    for (i = 0; i < ri; i++){
    

    does not use pointers.

    The function can be defined the following way as it is shown in the demonsytrative program below.

    #include <stdio.h>
    #include <string.h>
    
    char * reverse( char *s )
    {
        if ( *s )
        {
            for ( char *first = s, *last = s + strlen( s ); first < --last; ++first )
            {
                char c = *first;
                *first = *last;
                *last = c;
            }
        }
        
        return s;
    }
    
    int main( void ) 
    {
        char s1[] = "1";
        char s2[] = "12";
        char s3[] = "123";
        
        puts( reverse( s1 ) );
        puts( reverse( s2 ) );
        puts( reverse( s3 ) );
    }   
    

    The program output is

    1
    21
    321