Search code examples
cfunctioncharreversec-strings

Why I can't print first/last character right?


My output string needs to be palindrom of the input string. It works almost perfect but I am having problem with first character of the input string, my new string won't print it (in essence my new string won't print last character). Also strrev() does not work on Ubuntu so i need to do this without using that function.

#include <stdio.h>
#include <string.h>
int main(void){

    int i,j=0;

    char input_str[10];
    char new_str[10];

    printf("Enter characters:\n");

    gets(input_str);

    for(i=strlen(input_str)-1;i>0;i--){

        new_str[j]=input_str[i];
        j++;

    }

    printf("Output:\n");
    printf("%s", new_str);

    return 0;

}



Solution

  • For starters the function gets is unsafe function and is not supported by the C Standard.

    You should use the standard C function fgets.

    There are two problems with your code. The first one is in this loop

    for(i=strlen(input_str)-1;i>0;i--){
    
        new_str[j]=input_str[i];
        j++;
    
    }
    

    the index i equal to 0 is skipped from using it to copy the corresponding character of the source string.

    The second one is the destination array is not appended with the terminating zero character.

    Here is a demonstrative program that shows how a function that makes a reversed copy of a source string can be implemented.

    #include <stdio.h>
    #include <string.h>
    
    char * reverse_copy( char *dsn, const char *src )
    {
        size_t n = strlen( src );
    
        size_t i = 0;
    
        for ( ; i < n; i++ )
        {
            dsn[i] = src[n - i - 1];
        }
    
        dsn[i] = '\0';
    
        return dsn;
    }
    
    int main(void) 
    {
        enum { N = 10 };
        char input_str[N] = "";
        char new_str[N];
    
        printf( "Enter a string (less than %zu symbols): ", ( size_t )N );
    
        fgets( input_str, N, stdin );
    
        input_str[ strcspn( input_str, "\n" ) ] = '\0';
    
        printf( "\"%s\"\n", input_str );
        printf( "\"%s\"\n", reverse_copy( new_str, input_str ) );
    
        return 0;
    }
    

    The program output might look for example the following way

    Enter a string (less than 10 symbols): Hello
    "Hello"
    "olleH"