简体   繁体   中英

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'; 
}

Can someone tell me when i print out *r, why im missing the first character? eg, hello reversed is olle? thanks

The mistake is incrementing pointer with defreferencing, like *l++, and comparing the pointers by the value they point at. The fixed code would look like:

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'; 

}

Change to do-while:

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

*r = '\0';

Few of the checks are wrong. First while(*l != *start) The loop will exit without copying the last character.

So the check should be based on address.

while(l >= start)

Just you need to increment and decrement the pointers *l-- and *r++ is not you intend to do.

#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'; 
}

Note the while condition has changed and also the pointer arithmetic is right.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM