[英]trying to reverse 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;
}
我的代碼有什么問題嗎?我知道當字符串的長度是偶數但是它應該適用於奇數情況時,我放入while循環的條件不會起作用。
似乎有一個錯字
'#include<conio.h>
^^
C標准不再支持任何函數gets
。 相反,你應該使用標准函數fgets
。
這種情況
while(ptr1!=ptr2)
對於具有偶數個字符的字符串是錯誤的,因為它永遠不會等於false並且循環將是無限的。
以下陳述也是錯誤的
ptr1,ptr2=&str[0];
這里使用了逗號運算符,ptr1未初始化。
我想你的意思是
ptr1 = ptr2 = &str[0];
該程序可以通過以下方式編寫
#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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.