printf function won't print reversed string

85 Views Asked by At

I have to write a function which gets a string and then reverses it. I wrote this code, which gave me no compilation errors:

#include <stdio.h>
#include <string.h>
char *reverse(char *str);

int main(void){

    char string[100];
    printf("Insert the string to be inverted: ");
    gets(string);
    reverse(string);
    printf("Inverted string is: %s\n", string);
    }

char *reverse(char *str){

    char h;
    int i, j;
    for(i=0, j=strlen(str); i<j; i++, j--){

        h=str[i];
        str[i]=str[j];
        str[j]=h;
        }

    }

Only problem I get is that, apparently, printf won't print the reversed string. Can anyone help me?

2

There are 2 best solutions below

0
On

The reversed string has the terminator \0 at position 0.

1
On

strlen(str) gives you the size of the string, i.e. the index of the terminating null character.

You don't want to swap the null terminator, so strlen(str) - 1 is the index of the last character you want to swap.

Therefore, j should start at strlen(str) - 1.