Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trying to reverse a string inplace using two pointers

Tags:

c

pointers

#include<conio.h>          
#include<stdio.h>    

int main(void)    
{    
    char str[20];    
    char *ptr1,*ptr2;    
    printf("Enter string\n");    
    gets(str);    
    ptr1,ptr2=&str[0];    
    while(*ptr2!='\0')                  
    {    
        ptr2++;    
    }    
    ptr2--;    
    printf("rev_string =");    
    while(ptr1!=ptr2)    //this should work for when strlen=odd integer
    {    
        int temp=*ptr2;    
        *ptr2=*ptr1;    
        *ptr1=temp;    
        ptr1++;    
        ptr2--;    
     }    
    puts(str);    
    return 0;    
} 

whats wrong with my code?i know the condtion which i've put into the while loop is not gonna work when length of the string is even but it should work for odd cases.

like image 292
Prince Vijay Pratap Avatar asked Aug 25 '26 15:08

Prince Vijay Pratap


1 Answers

It seems there is a typo

'#include<conio.h>          
^^

The C standard does not support any more function gets. Instead you should use standard function fgets.

This condition

while(ptr1!=ptr2)

is wrong for strings with an even number of characters because it will be never equal to false and the loop will be infinite.

The following statement is also wrong

ptr1,ptr2=&str[0];    

Here is used the comma operator and ptr1 is not initialized.

I think you mean

ptr1 = ptr2 = &str[0];    

The program can be written the following way

#include<stdio.h>    

int main( void )    
{    
    char str[20];    
    char *ptr1,*ptr2;

    printf( "Enter a string: ");    
    fgets( str, sizeof( str ), stdin );

    ptr2 = str;

    while ( *ptr2 != '\0' ) ++ptr2;                  

    if ( ptr2 != str && *( ptr2 - 1 ) == '\n' ) *--ptr2 = '\0';

    printf( "rev_string = " );    

    ptr1 = str;

    if ( ptr1 != ptr2 )
    {
        for ( ; ptr1 < --ptr2; ++ptr1 )
        {    
            int temp = *ptr2;    
            *ptr2 = *ptr1;    
            *ptr1 = temp;
        }    
    }

    puts( str );

    return 0;    
} 
like image 134
Vlad from Moscow Avatar answered Aug 29 '26 00:08

Vlad from Moscow



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!