Search code examples
cstringreverse

What's wrong in this program ? Explain If Possible. C Language - Strings


    //Program to get reverse of entered string.
#include<stdio.h>

#include<string.h>

void rev(char *a, char *b);

int main()

  {

    char a[50];
    char b[50];

    printf("Enter String: ");
    gets(a);
    printf("\n");
    rev(a, b);

    return 0;
  }

void rev(char *a, char *b) 

{

  int i;

  int n = strlen(a) - 1;

  printf("Lenght of string : %d\n", n);

  printf("\n");

  for(i=0; i<n; i++)

  {

    b[i] = a[n];

    n--;

  }
  
  b[i] = '\0';

  printf("Reverse : %s", b);

}

Solution

  • Here is a correct version of that code, I have added some comments to make the changes clear

    // Program to get reverse of entered string.
    #include <stdio.h>
    #include <string.h>
    
    void rev(char *a, char *b);
    
    int main() {
      char a[50];
      char b[50];
    
      printf("Enter String: ");
      // gets() should be fgets(), cause gets() is dangerous and even deprecated 
      fgets(a, sizeof a, stdin);
      printf("\n");
      rev(a, b);
      return 0;
    }
    
    void rev(char *a, char *b) {
      int i;
      int n = strlen(a) - 1;
      printf("Length of string : %d\n", n);
      printf("\n");
      // you should subtract `i` from `n` instead of decrementing `n` cause the loop depends on it
      for(i = 0; i <= n; i++) {
        b[i] = a[n - i];
      }
      b[i] = '\0';
      printf("Reverse : %s", b);
    }