[Courses] [C] What is wrong here??
pete at flatline.org.uk
Tue Aug 13 18:45:51 EST 2002
On Tue, 13 Aug 2002, Anand R wrote:
> My purpose is to accept a string input from the user, and check whether it
> is a palindrome or not. I tried hard to figure out how to write a C function
> to reverse a string, and how to store this reversed value in another string.
> If somebody could tell me where I am going wrong here. Any pointers to
> understand this better would be greatly appreciated.
OK. Laura has already suggested that you draw what memory looks like -
I'll second that as it's the only way to really understand what's going
I also reccomend thinking "there is no such thing as a string in
C". Because they're not first-class data types, things like returning
strings and passing them as arguments are fraught with possible problems.
> char strrev(char array);
> int main()
> char string1;
Add a "char temp;" as well. It's a good idea to #define STRINGSIZE 10
as well, it helps if you want to change it later.
> fprintf(stderr,"\nEnter a string: ");
Good to see you're avoiding buffer overruns here :)
At this point I would:
temp[STRINGSIZE-1]=0; /* Ensure null termination */
> printf("\nThe reversed string is: %s\n",temp);
.. and then I would write a strrev that reversed a string in-place, by
taking a pointer to the start and a pointer to the end, then move the
pointers in swapping values along the way.
Reversing a string in-place means that you don't have to do any memory
allocation in strrev(). However, if you do this then you have to take a
copy of the original string or you can't compare it against anything
Peter Clay | Campaign for _ _| .__
| Digital / / | |
| Rights! \_ \_| |
More information about the Courses