Harrison
Harrison

Reputation: 25

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

Upvotes: 2

Views: 99

Answers (3)

Marte Valerio Falcone
Marte Valerio Falcone

Reputation: 455

Because you should change your second while condition to while (count >= 0)

Upvotes: 0

Daniel Kleinstein
Daniel Kleinstein

Reputation: 5512

Notice your second while condition: while (count > 0). You aren't including your last character - e.g. 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.

Upvotes: 4

the busybee
the busybee

Reputation: 12673

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.)

Upvotes: 4

Related Questions