>did any one get this problem when solving the above prob
Only those that wrote the same broken code as you.
>i=sizeof temp
temp is a pointer, so i would most likely be 2 or 4, not the size of str, and most certainly not the size of a variable length string entered by the user. This would work better:
Code:
#include <stdio.h>
#include <string.h>
void rev ( char str[] );
int main ( void )
{
char str[25];
while ( fgets ( str, sizeof str, stdin ) != NULL )
rev ( str );
return 0;
}
void rev ( char str[] )
{
int i = 0;
int j = strlen ( str ) - 1;
char temp[25];
while ( j >= 0 )
temp[i++] = str[j--];
temp[i] = '\0';
printf ( "%s\n", temp );
}
But since it's trivial to reverse a string in-place, you don't need the error prone temporary array:
Code:
#include <stdio.h>
#include <string.h>
void rev ( char str[] );
int main ( void )
{
char str[25];
while ( fgets ( str, sizeof str, stdin ) != NULL ) {
rev ( str );
printf ( "%s\n", str );
}
return 0;
}
void rev ( char str[] )
{
int i = 0;
int j = strlen ( str ) - 1;
while ( i < j ) {
char save = str[i];
str[i++] = str[--j];
str[j] = save;
}
}