c
  • pointers
  • 2015-05-23 29 views 3 likes 
    3
    #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循環condtion是不是要去工作時的字符串的長度是偶數,但它扭轉一個字符串就地應該適用於奇怪的情況。嘗試使用兩個指針

    回答

    4

    似乎有一個錯字

    '#include<conio.h>   
    ^^ 
    

    C標準不支持任何更多的功能gets。相反,你應該使用標準功能fgets

    這種情況

    while(ptr1!=ptr2) 
    

    是錯誤的,有偶數個字符的字符串,因爲這將是永遠等於假,循環將是無限的。

    下面的語句也是錯誤的

    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;  
    } 
    
    +1

    是的,我已經提到,條件(PTR1!= PTR2)不是連長度會工作字符串,但它應該適用於奇數,只是想知道爲什麼它也不適用於奇數長度。 –

    +1

    @Peince Vijay Pratap查看我更新的帖子。 –

    +1

    你能告訴我爲什麼你這樣做嗎? if(ptr2!= str && *(ptr2 - 1)=='\ n')* - ptr2 ='\ 0'; –

    相關問題