Search code examples
creversec-stringsfunction-definition

Function to reverse print


Yesterday I had to solve an exam exercise, which, unfortunately, I failed.. The exercise was to create a function in C with the following rules:

  • Write a function that takes a string and displays the string in reverse order followed by the newline.
  • Its prototype is constructed like this : char *ft_rev_print (char *str)
  • It must return its argument
  • Only allowed to use function 'write'(so no printf or others)

With that information I wrote :

int     ft_strlen(char *str) /*to count the length of the original string*/
{
    int     i;
    i = 0;
    while (str[i])
            i++;
    return (i);
}
char    *ft_rev_print (char *str)
{
    int     i;

    i = ft_strlen(str);
    while (i)
    {
            write (1, (str +1), 1);
            i--;
    }
    return (str);             /*returning its argument */
}

int     main(void)     /*IT HAD TO WORK WITH THIS MAIN, DID NOT WROTE THIS MYSELF!*/
{
    ft_rev_print("rainbow dash");
    write(1, "\n", 1);
    return (0);
}

I tried for ages to get it to work, but failed.. So now I'm breaking my head over this. What did i do wrong ? What did i miss?

Thanks in advance !


Solution

  • For starters your teachers are not enough qualified. The functiuon should be declared at least like

    char * ft_rev_print( const char *str );
                         ^^^^^
    

    because the passed string is not changed within the function.

    You forgot to call the function ft_strlen.

    It seems you mean

    i = ft_strlen( str );
    

    As a result this loop

    i = 0;
    while (i)
    {
        //...
    }
    

    is never executed because initially i is equal to 0 and the condition of the loop at once evaluates to false.

    Also in this call

    write (1, (str +1), 1);
              ^^^^^^^^
    

    you are always trying to output the second symbol of the string.

    Also the output of the new line character '\n' should be within the function according to its description.

    The function can look the following way as it is shown in the demonstrative program below (instead of the non-standard function write I will use the function putchar but you can substitute it for write yourself)

    #include <stdio.h>
    
    char * ft_rev_print( const char *str )
    {
        const char *p = str;
        
        while ( *p ) ++p;
        
        while ( p != str ) putchar( *--p );  // substitute the call of putchar for write( 1, *--p, 1 )
        
        putchar( '\n' );  // substitute the call of putchar for write( 1, "\n", 1 )
        
        return ( char * )str;
    }
    
    int main(void) 
    {
        ft_rev_print( "rainbow dash" );
        
        return 0;
    }
    

    The program output is

    hsad wobniar