簡體   English   中英

為什么我的反向功能在C語言中不起作用?

[英]Why does my reverse function not work in C?

void str_reverse(char *l, char *r){
    char *start = l; //gives while loop place to stop, the start of the string
    while (*l != '\0'){
        *l++;
    } //loops the to the end terminator

    *l--; //last character

    while (*l != *start){
        *r = *l;
        *l--;
        *r++;
    } // adds the string from back to front to new string

    *r = '\0'; 
}

當我打印出* r時,有人可以告訴我,為什么我錯過了第一個字符? 例如,你好,是奧勒嗎? 謝謝

錯誤是使用* l ++之類的具有取消引用的指針來遞增指針,並將指針與它們所指向的值進行比較。 固定代碼如下所示:

void str_reverse(char *l, char *r){

char *start = l; //gives while loop place to stop, the start of the string
while (*l != '\0'){
    l++;
    } //loops the to the end terminator

l--; //last character

while (l >= start){
    *r = *l;
    l--;
    r++;
} // adds the string from back to front to new string

*r = '\0'; 

}

更改為做時:

do {
   *r = *l;
   l--;
   r++;
   // adds the string from back to front to new string
} while (l != start);

*r = '\0';

很少有支票是錯誤的。 首先while(*l != *start)循環將退出而不復制最后一個字符。

因此,支票應基於地址。

while(l >= start)

只是您需要遞增和遞減指針*l--*r++並非您打算這樣做。

#include <stdio.h>
#include <string.h>

void str_reverse(char *l, char *r){

char *start = l; //gives while loop place to stop, the start of the string
while (*l != '\0'){
    *l++;
    } //loops the to the end terminator

*l--; //last character

while (l >= start){
    *r = *l;
    l--;
    r++;
} // adds the string from back to front to new string

*r = '\0'; 


}
int main()
{
   char a[20] = "somestring";
   char b[20];
   str_reverse(a,b);
   printf("%s",b);
   return 0;
}
void str_reverse(char *l, char *r) {

    char *start = l; //gives while loop place to stop, the start of the string

    while (*l != '\0'){
        l++;
    } //loops the to the end terminator

    l--; //skips \0

    while (l >= start){
        *r = *l;
        l--;
        r++;
    } // adds the string from back to front to new string

    *r = '\0'; 
}

請注意,while條件已更改,並且指針算法正確。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM