Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 207
Deno Avatar asked Dec 29 '25 12:12

Deno


2 Answers

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
like image 61
Vlad from Moscow Avatar answered Jan 01 '26 04:01

Vlad from Moscow


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.

like image 38
CiaPan Avatar answered Jan 01 '26 05:01

CiaPan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!