Trying to flip a string inplace using two 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;
}
What's wrong with my code? I know that the condition I put in the while loop won't work when the string length is even, but it should work for the odd cases.
+3
source to share
1 answer
There seems to be a typo
'#include<conio.h>
^^
The C standard no longer supports the function gets
. You should use a standard function instead fgets
.
This condition
while(ptr1!=ptr2)
is not true for strings with an even number of characters, because it will never be false and the loop will be infinite.
Also the following statement is not true
ptr1,ptr2=&str[0];
The comma operator is used here and ptr1 is not initialized.
I think you mean
ptr1 = ptr2 = &str[0];
The program can be written as follows
#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;
}
+4
source to share