简体   繁体   中英

Program printing wrong output

Why is the following code printing !notreblo! instead of !notrebloH ? Where is the ! coming from? I am trying to write a program that reverses an array and I am using the main function to test the rev_string function.

#include <stdio.h>

int main(void)
{ 
   char s[11] = "Holberton!";

   printf("%s\n", s);
   rev_string(s);
   printf("%s\n", s);
   return (0);
}

void rev_string(char *s)
{
    char new[500];
    int count, newcount;

    count = 0, newcount = 0;

    while (*(s + count) != '\0')
    {
            *(new + count) = *(s + count);
            count++;
    }

    count--;

    while (count > 0)
    {
            *(s + newcount) = *(new + count);
            count--;
            newcount++;
    }
}

The second while does not copy the first character, because the last character copied is at index 1. The condition tells it so: count > 0 .

Change it to count >= 0 .

(+1 for the famous "one-off" error. If I got 1 cent each time, I'll be a rich person.)

Notice your second while condition: while (count > 0) . You aren't including your last character - eg if count == 3 (3 characters to reverse), you will only iterate twice - and your third character will not be written. You need to change the condition to while (count >= 0) .


As a bonus, the function you are implementing is better known as strrev - and it can be implemented without an additional buffer.

因为您应该将第二个 while 条件更改为while (count >= 0)

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