-1
#include<stdio.h>

void strrevud(char * str , char* rev_str ){
    int i=0,j=0;
    while(str[i]!='\0')
        i++;
    for(j=0 ; j<=i ;j++)
        *(rev_str + j) = *(str + (i-j));
    }

int main(){
    char a[50],b[60];
    gets(a);
    strrevud(a,b);
    printf("\n Reversed string is ");
    puts(b);
    return 0;
}

strrevud is a function to reverse a string. It takes the address of two strings as arguments. If I print rev_str in strrevud it is printed, but in main it is not shown.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • You print `b` *twice*. And you seem to forget to add the null-terminator to `b` (`rev_str`). – Some programmer dude Jun 24 '21 at 04:24
  • 3
    Oh, and never ***ever*** use `gets`. It's so [dangerous](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) it have even been removed from the C language specification. Use e.g. [`fgets`](https://en.cppreference.com/w/c/io/fgets) instead. – Some programmer dude Jun 24 '21 at 04:25
  • It seems like this is the time to learn how to use a *debugger* to be able to step through the code statement by statement while monitoring variables and their values. The problem solved by [MikeCat's answer](https://stackoverflow.com/a/68109642/440558) should have been very obvious within just a few seconds if using a debugger. – Some programmer dude Jun 24 '21 at 04:35

1 Answers1

2

Your strrevud function will reverse the entire string data including the terminating null-character. Therefore, the terminating null-character will come to the first element and therefore the result will be a string with zero characters.

You have to treat the terminating null-character separately.

Also you shouldn't use gets(), which has unavoidable risk of buffer overrun, deprecated in C99 and removed from C11.

#include<stdio.h>
#include<string.h>
void strrevud(char * str , char* rev_str ){
    int i=0,j=0;
    while(str[i]!='\0')
        i++;
    /* reverse the string data without terminating null-character */
    for(j=0 ; j<i ;j++)
        *(rev_str + j) = *(str + (i-1-j));
    /* add a terminating null-character */
    *(rev_str + i) = '\0';
}
int main(){
    char a[51],b[60]; /* allocate one more for a to allow a newline character to be stored */
    fgets(a,sizeof(a),stdin);
    strtok(a,"\n"); /* remove newline character */
    strrevud(a,b);
    printf("\n Reversed string is ");
    puts(b);
    return 0;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70