How to reverse a string with pointers only?

693 views Asked by At

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);
}
3

There are 3 answers

4
Vlad from Moscow On BEST ANSWER

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
13
0___________ On

Your code has plenty of issues (bugs ):

char ri = strlen((s) - 1); has to be size_t ri = strlen((s)) - 1;

Other code is very hard to analyze as you use not self explanatory variable names.

Here you have a bit more simple code and much easier to analyse.

char *reverseString(char *str)
{
    char *wrk = str, *end;
    if(str && *str)
    {
        end = str + strlen(str) - 1;
        while(end > wrk)
        {
            char temp = *wrk;
            *wrk++ = *end;
            *end-- = temp;
        }
    }
    return str;
}


int main(void)
{
    char str[] = "1234567890";
    printf("reversed: %s\n", reverseString(str));
}
3
CiaPan On

A simple solution:

char *sl = sf;
while (*sl != 0)
    ++ sl;
-- sl; 
while (sf < sl)
{
    char c = *sf;
    *sf = *sl;
    *sl = c;

    ++sf, --sl;
}

Find the end of the string by skipping all characters until you find the NUL (zero) character.
Then step back one character (decrement sl) so that you have pointers to the first and the last character of the string.

Then walk both pointers towards one another and swap characters until the pointers meet or cross.