1

**i am trying to reverse a string so what i am trying is to take the string to its last position and from there i am storing it to a new character array and printing that but not getting desired output **

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
        char c[10];
        printf("Enter the string:\n");
        gets(c);
        rev(c);
        return 0;
}

void rev(char c[])
{
        int i = 0,j = 0;
        char s[10];
        while(c[j] ! = '\0')//reaching to end of string
        {
                j++;
        }
        while(s[i] ! = '\0')
        {
                s[i] = c[j];//copying string c from end into string s from begining
                i++;
                j--;
        }
        s[i+1]='\0';
        printf("The string after reverse: %s",s);//printing reversed string
}
Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
Ani
  • 53
  • 1
  • 7
  • Not an anwer but in line `c[j] ! = '\0'`, never put space between `!` and `=`. – Mohit Jain Dec 09 '15 at 05:48
  • 1
    `while(s[i] != '\0')` is wrong. You never initialize `s[10]` so it contains gargabe. And garbage can be `\0` which will cause you while to abort instantly. – RedX Dec 09 '15 at 05:51
  • In your second loop, you're checking `s[i]` in the while test before ever storing anything into `s`, so your behavior will be random. – Tom Karzes Dec 09 '15 at 05:51
  • Off >> Where are you from, Ani ? Why don't you use `strlen` ? – Imobilis Dec 09 '15 at 06:10

2 Answers2

2
while(s[i] ! = '\0')

In above line s[i] is uninitialized and hence you are invoking undefined behaviour by accessing uninitialized value and thus incorrect result.

To fix this, you can rewrite the condition as:

while(j >= 0)

Apart from these, for sane result, you need following two changes:

  1. The final termination should be re-written as:

    s[i]='\0';

  2. The initial value of j should be decremented by 1. (As c[j] would point to the null character)

as i is now already pointing past the size of c string.

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
0

problem is when you use gets() the buffer is usually dirty. I would suggest you use fflush(stdin) before the gets().

Also the last line where you say s[i+1] = '\0' should be s[i] = '\0' the i already was incremented by one after the last execution of the loop.

And as said above it shouldnt be while (s[i] != '\0') s is not initialized so God knows whats in there. make it like while ( j >=0) and it should work.

IWHKYB
  • 481
  • 3
  • 11
  • 1
    [`fflush(stdin)`](http://stackoverflow.com/questions/22901901/what-does-fflushstdin-do-in-c-programing) causes undefined behaviour. It will be good to sugest not to use `gets` instead. – ameyCU Dec 09 '15 at 06:02