Search code examples
cloopsreversec-strings

Create a duplicate of a string but reversed in C


I am trying to create a duplicate of a string but reversed. I am able to strcpy each char and print them individually but I get nothing when I print the entire duplicate string.

#include <unistd.h>
#include <stdio.h>
#include <string.h>

int     main(void)
{
    char    str[101] = "Lieur a Rueil";
    char    temp[101];
    int     i;
    int     j;

    i = 0;
    j = strlen(str);

    while (str[j] - 1)
    {
        strcpy(&temp[i], &str[j]);
        printf("%c", temp[i]);
        j--;
        i++;
    }
    printf("\n");
    printf("temp: %s\n", temp);
    return (0);
}

output:

lieuR a rueiL
temp:

Solution

  • This while loop

    while (str[j] - 1)
    {
        strcpy(&temp[i], &str[j]);
        printf("%c", temp[i]);
        j--;
        i++;
    }
    

    does not make a sense. The condition of the loop can invoke undefined behavior due to accessing memory beyond the array. The same problem exists with the call of strcpy.

    The main logic of the program can be implemented simpler. For example

    size_t i = 0;
    
    for ( size_t j = strlen( str ); j-- != 0; i++ )
    {
        temp[i] = str[j];
    }
    
    temp[i] = '\0';
    
    printf("\ntemp: %s\n", temp);
    

    Here is a demonstrative program.

    #include <stdio.h>
    #include <string.h>
    
    int main(void) 
    {
        char str[] = "Lieur a Rueil";
        char temp[sizeof( str )];
        
        size_t i = 0;
    
        for ( size_t j = strlen( str ); j-- != 0; i++ )
        {
            temp[i] = str[j];
        }
    
        temp[i] = '\0';
    
        printf("\ntemp: %s\n", temp);   
    }   
    

    The program output is

    temp: lieuR a rueiL