Home > other >  Create a duplicate of a string but reversed in C
Create a duplicate of a string but reversed in C

Time:09-28

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:

CodePudding user response:

#include <stdio.h>
#include <string.h>
#include <stdint.h>
 
int main(void)
{
    char    str[101] = "Lieur a Rueil";
    char    temp[101];
    size_t  sz = strlen(str);
 
    for(size_t i=0;i<sz;   i)
    {
        temp[sz-i-1] = str[i];
    }
    temp[sz]=0;
 
    printf("temp: %s\n", temp);
    return (0);
}

Output:

temp: lieuR a rueiL

CodePudding user response:

With minimal changes to original code:

#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);

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

CodePudding user response:

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
  • Related