-
manual string reverse
enlighten me with my mistake
Code:
#include<stdio.h>
int str_rev(char *s1)
{
char str2[50];
char *s2=str2;
int i=0,len=0;
while(*(s1+i) != '\0')
i++;
i--;
while(i!=0)
{
*(s2+len)=*(s1+i);
i--;
len++;
}
// *(s2+len)='\0';
// printf("\nreversed string == > %s",s2);
while(*(s2+i) != '\0')
{
*(s1+i)=*(s2+i);
}
*(s1+i)='\0';
printf("\nreversed string 2 ==> %s\n",s1);
return 0;
}
int main()
{
char str[20];
char *s1 = str;
printf("\nEnter string\n");
scanf("%s",s1);
str_rev(s1);
return 0;
}
-
It's a lot easier to track down a problem when we know what the problem is - are you getting compiler errors? runtime errors? And if so, what do the errors say and where do they occur? Is the program running but just outputting incorrect output? And if so, what are your test inputs / outputs?
-
i'm getting an incorrect output.... no errors... sorry for not specifying these things in my first post...
Code:
./a.out
Enter string
abcd
dfkj
dsaf
asf
nkl
^Z
[1]+ Stopped
-
all the characters in the output screen are what i typed
-
Code:
char str[20];
char *s1 = str;
printf("\nEnter string\n");
scanf("%s",s1);
str_rev(s1);
You don't have to do that, you know. You can use the name of an array by itself to treat it as a pointer (to the first element of the array). In fact, "array" is just like "&array[0]".
Code:
char str[20];
scanf("%s", str);
Also, fgets() is better suited to user input than scanf("%s") . . . SourceForge.net: Scanf woes - cpwiki
Finally, there are easier ways to reverse a string. Consider this pseudo-code:
Code:
set start to start of string
set end to point to the end of the string
while start < end:
swap *start and *end
increment start, decrement end
-
-
As to what could be going wrong *(s2+i) != '\0' doesn't ever have to be true, since you never terminate the s2 string....
-
Well, not to mention that i is never changed in this loop, so it's probably infinite.
Code:
while(*(s2+i) != '\0')
{
*(s1+i)=*(s2+i);
}
-
still.... i'm not able to find my error.....
***incremented the value of i in the while loop**** that was very silly from my side
-
If you'd said at the beginning "it hangs when I run it," then we'd have known immediately to look for an infinite loop and helped you that much faster. So why don't you tell us what it does now . . . ?
Incidentally, this loop
Code:
while(i!=0)
{
*(s2+len)=*(s1+i);
i--;
len++;
}
won't process *(s1 + 0). So the first element of the string probably won't be copied.
-
the pseudo code helped me.... thanks!!