Solution for Exercise 19-26

ex1926

#include <stdio.h>

char *strrev(char *input);

int main()
{
    char string[64];

    printf("Type some text: ");
    fgets(string,62,stdin);
    puts(strrev(string));

    return(0);
}

char *strrev(char *input)
{
    static char output[64];
    char *i,*o;

    i=input; o=output;

    while(*i++ != '\n')
        ;
    i--;

    while(i >= input)
        *o++ = *i--;
    *o = '\0';

    return(output);
}

Notes

* The i-- statement at Line 26 backs up to the newline character, not before that character as mentioned in the text. The newline appears in the output. If you want to backup to the position before the newline, set Line 26 to read:

* To prove that the static variable type is required at Line 18, remove it: Edit it out of the code. When you compiler, you may see a warning error:

The code may run, as long as nothing else clobbers the string sitting in memory. That's not a guarantee, however, hence the warning. No, it's just better to use static and ensure that the string is retained after the function returns.