0

I was refreshing my C knowledge and I happened to cross this program for reversing a string. I have a feeling that the last character of the final reversed string should be assigned '\0' value else it may have a garbage value. Could you please tell if this code is correct or needs to be modified? Thanks in advance!

#include<stdio.h>
#include<string.h>

void main()
{
  char str[100],temp;
  int i,j=0;

  printf("nEnter the string :");
  gets(str);

  i=0;
  j=strlen(str)-1;

  while(i<j)
  {
    temp=str[i];
    str[i]=str[j];
    str[j]=temp;
    i++;
    j--;
  }

  printf("nReverse string is :%s",str);
  return(0);
}
honk
  • 9,137
  • 11
  • 75
  • 83
user3033933
  • 57
  • 2
  • 8
  • `I have a feeling that the last character of the final reversed string should be assigned '\0' value` did you try it? – yamafontes Mar 07 '14 at 17:16
  • 5
    You're swapping the characters in place in the same piece of memory, so the final '\0' is still there and still at the end of the string. – Lencho Reyes Mar 07 '14 at 17:17
  • 2
    Have you looked for duplicates? There are 8 possible duplicates shown under the 'Related' column. It's practically certain that they all have workable solutions that would enlighten you. Also, you should **never** use `gets()`. It is no longer a standard C function (hooray!) and any program that uses it cannot defend itself against abuse, whether accidental or deliberate. The standard replacement is `fgets()`, but remember that it includes the newline where `gets()` does not. – Jonathan Leffler Mar 07 '14 at 17:18
  • 2
    [NEVER use `gets()`](http://stackoverflow.com/q/1694036/10077) – Fred Larson Mar 07 '14 at 17:18
  • cant you do this more simply with a recursive function? – AnthonyLambert Mar 07 '14 at 17:20
  • main return type should be `int main` – tesseract Mar 07 '14 at 17:22

1 Answers1

0

as per man gets :

...the buffer is terminated with a 0.

I think you are all set!

problemPotato
  • 589
  • 3
  • 8
  • 3
    Also per `man gets`: "Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead." – Fred Larson Mar 07 '14 at 17:22
  • 1
    `gets` doesn't even in C11 – michaelmeyer Mar 07 '14 at 17:36